Pandas 注意事项

Pandas 注意事项和陷阱

在Pandas中使用If/Truth语句

当您使用布尔运算符if或when,or或or not,尝试将某些内容转换为bool时,有时会引发一个错误。错误是怎么发生的目前尚不清楚。Pandas提出了一个ValueError异常。

importpandasaspdifpd.Series([False,True,False]):print'IamTrue'

运行结果如下:

ValueError:ThetruthvalueofaSeriesisambiguous.Usea.empty,a.bool()a.item(),a.any()ora.all().

在这种情况下,不清楚该怎么处理。这个错误暗示了是使用None或是其中任何一个。.

importpandasaspdifpd.Series([False,True,False]).any():print("Iamany")

运行结果如下:

Iamany

要在布尔上下文中评估单元素Pandas对象,请使用.bool()方法-

importpandasaspdprintpd.Series([True]).bool()

运行结果如下:

True

位布尔值

像==和!之类的按位布尔运算符=将返回一个布尔序列,这几乎总是需要的。

importpandasaspds=pd.Series(range(5))prints==4

运行结果如下:

0False1False2False3False4Truedtype:bool

isin操作

这将返回一个布尔系列,显示布尔值中的每个元素是否完全包含在传递的值序列中。

importpandasaspds=pd.Series(list('abc'))s=s.isin(['a','c','e'])prints

运行结果如下:

0True1False2Truedtype:bool

重建索引 vs ix索引

许多用户会发现自己使用ix索引功能作为从Pandas对象中选择数据的一种简洁方法:

importpandasaspdimportnumpyasnpdf=pd.DataFrame(np.random.randn(6,4),columns=['one','two','three','four'],index=list('abcdef'))printdfprintdf.ix[['b','c','e']]

运行结果如下:

onetwothreefoura-1.5820251.3357730.961417-1.272084b1.4615120.111372-0.0722250.553058c-1.2406710.7621851.511936-0.630920d-2.380648-0.0299810.1964890.531714e1.8467460.1481490.275398-0.244559f-1.842662-0.9331952.3039490.677641onetwothreefourb1.4615120.111372-0.0722250.553058c-1.2406710.7621851.511936-0.630920e1.8467460.1481490.275398-0.244559

当然,在这种情况下,这完全等同于使用reindex方法:

importpandasaspdimportnumpyasnpdf=pd.DataFrame(np.random.randn(6,4),columns=['one','two','three','four'],index=list('abcdef'))printdfprintdf.reindex(['b','c','e'])

运行结果如下:

onetwothreefoura1.6390811.3698380.261287-1.662003b-0.1733590.242447-0.4943840.346882c-0.1064110.6235680.282401-0.916361d-1.078791-0.612607-0.897289-1.146893e0.4652151.552873-1.8419590.329404f0.966022-0.1900771.3242470.678064onetwothreefourb-0.1733590.242447-0.4943840.346882c-0.1064110.6235680.282401-0.916361e0.4652151.552873-1.8419590.329404

有人可能会得出结论,ix和reindex基于此是100%等效的。除了整数索引的情况外,都是如此。例如,上述操作可以代替地表示为:

importpandasaspdimportnumpyasnpdf=pd.DataFrame(np.random.randn(6,4),columns=['one','two','three','four'],index=list('abcdef'))printdfprintdf.ix[[1,2,4]]printdf.reindex([1,2,4])

运行结果如下:

onetwothreefoura-1.015695-0.5538471.106235-0.784460b-0.527398-0.518198-0.710546-0.512036c-0.842803-1.0503740.7871460.205147d-1.238016-0.749554-0.547470-0.029045e-0.0567881.063999-0.7672200.212476f1.1397140.0361590.2019120.710119onetwothreefourb-0.527398-0.518198-0.710546-0.512036c-0.842803-1.0503740.7871460.205147e-0.0567881.063999-0.7672200.212476onetwothreefour1NaNNaNNaNNaN2NaNNaNNaNNaN4NaNNaNNaNNaN

重要的是要记住,重新索引仅是严格的标签索引。在索引包含例如整数和字符串的出错情况下,这可能导致某些可能令人意想不到的结果。

编辑于2024-05-20 14:47