Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么pandas中数据帧列(对象类型系列)上没有参数的all()返回列中的最后一个值_Python_Pandas_Numpy - Fatal编程技术网

Python 为什么pandas中数据帧列(对象类型系列)上没有参数的all()返回列中的最后一个值

Python 为什么pandas中数据帧列(对象类型系列)上没有参数的all()返回列中的最后一个值,python,pandas,numpy,Python,Pandas,Numpy,我有一个类似这样的代码 dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"], "capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"], "area": [8.516, 17.10, 3.286, 9.597, 1.221], "population": [200.4, 143.5, 1252,

我有一个类似这样的代码

   dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
   "capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
   "area": [8.516, 17.10, 3.286, 9.597, 1.221],
   "population": [200.4, 143.5, 1252, 1357, 52.98] }

   import pandas as pd
   brics = pd.DataFrame(dict)

   print(brics['capital'].all())
   #the above code prints Pretoria

   print(brics['area'].all())
   #the above code prints True

   print(brics['population'].all())
   #the above code prints True

   print(brics['country'].all())
   #the above code prints South Africa

我的问题是,为什么代码会为float类型系列打印True,而为object类型打印列中的最后一个值。我想要一个只说“真”或“假”的结果。请帮帮我。

您观察到的行为正好反映了NumPy
对象的行为
dtype数组:

这并不奇怪,因为熊猫库是基于NumPy阵列构建的。您可以先显式转换为
bool
,以获得所需的结果:

brics_np[:, 0].astype(bool).all()     # True
brics_np[:, 1].astype(bool).all()     # True
brics['capital'].astype(bool).all()   # True
brics['country'].astype(bool).all()   # True

np.array(['', 'hello'], dtype=object).astype(bool).all()  # False

最后一个示例演示了空字符串将产生
False
,因为
bool(“”)
返回
False

brics.all()['capital']
。也就是说,如果您选择了数据帧,请选择“全部”
,然后再查找该系列。@Roope感谢您的回答。您能告诉我为什么上面的代码为float类型系列打印True,而为object类型打印列的最后一个值吗?不知道,至少看起来不太明显。
brics_np[:, 0].astype(bool).all()     # True
brics_np[:, 1].astype(bool).all()     # True
brics['capital'].astype(bool).all()   # True
brics['country'].astype(bool).all()   # True

np.array(['', 'hello'], dtype=object).astype(bool).all()  # False