当在pandas数据帧中应用all()时,它会返回True,尽管有些值是false



我有以下数据帧:

import pandas as pd
numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(numbers,columns=['set_of_numbers'])
df['equal_or_lower_than_4?'] = df['set_of_numbers'].apply(lambda x: 'True' if x <= 4 else 'False')
print (df)
set_of_numbers equal_or_lower_than_4?
0               1                   True
1               2                   True
2               3                   True
3               4                   True
4               5                  False
5               6                  False
6               7                  False
7               8                  False
8               9                  False
9              10                  False

当我尝试在最后一列应用all((函数时,它会返回True,尽管有些值是False

all(df['equal_or_lower_than_4?'])
#Out[29]:
#True
  1. 您可以通过使用:df['set_of_numbers'] <= 4来简化代码

import pandas as pd
numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(numbers,columns=['set_of_numbers'])
df['equal_or_lower_than_4?'] = df['set_of_numbers'] <= 4

Out[69]: 
0     True
1     True
2     True
3     True
4    False
5    False
6    False
7    False
8    False
9    False
Name: equal_or_lower_than_4?, dtype: bool
  1. 为什么all(df['equal_or_lower_than_4?'])返回True?原因是all()被定义为:

如果迭代中的所有项都为True,则all((函数返回True,否则返回False。

如果可迭代对象为空,那么all((函数也会返回True。

熊猫。如果序列不为空,则它等于True。所以all((只是检查:all([True](,因为只有一个非空的pd.Series作为参数提供。要检查其中的每个元素是否为True,可以使用np.sum((或all(df['equal_or_lower_than_4?'].tolist(((

import numpy as np
print(np.all(df['equal_or_lower_than_4?']))
#False

最新更新