np.ologic_or与reduce返回不同​​的结果

时间:2019-10-04 03:42:10

标签: python pandas numpy

np.logical_orfunctools.reduce返回不同的结果。

kdf = pd.DataFrame(data={'col1' : [' False', 1, np.nan], 'dt': [datetime.now(), ' 2018-12-12', '2019-12-12'], 'bool': 
                         [False, True, True], 'i': [1,2,'3'], 'bnan': [False, True, np.nan], 'col2': [' True ', False, 'False']})

print([kdf[i].str.contains('^\s*F') for i in ['col1', 'col2']])

# [0    True
# 1     NaN
# 2     NaN
# Name: col1, dtype: object, 0    False
# 1      NaN
# 2     True
# Name: col2, dtype: object]

您可能会看到它返回了预期的输出,但是当我们用np.logical_or重用它时,它将为第三行而不是Nan返回True

from functools import reduce
reduce(np.logical_or, [kdf[i].str.contains('^\s*F') for i in ['col1', 'col2']])

# 0    True
# 1     NaN
# 2     NaN
# dtype: object

但是np.logical_or(np.nan, True)返回True。我希望reduce将功能应用于所有列表项,即

kdf['col1'].str.contains('^\s*F') | kdf['col2'].str.contains('^\s*F')

我想念什么吗?

1 个答案:

答案 0 :(得分:1)

我认为这是一个错误,要正确处理NaN,应将其替换为一些布尔值,例如通过False参数移至na=False

from functools import reduce
a = reduce(np.logical_or, [kdf[i].str.contains('^\s*F') for i in ['col1', 'col2']])
print (a)
0    True
1     NaN
2     NaN
dtype: object

b = np.logical_or.reduce([kdf[i].str.contains('^\s*F') for i in ['col1', 'col2']])
print (b)
[True nan nan]

c = kdf['col1'].str.contains('^\s*F') | kdf['col2'].str.contains('^\s*F')
print (c)
0     True
1    False
2    False
dtype: bool

from functools import reduce
a = reduce(np.logical_or, [kdf[i].str.contains('^\s*F', na=False) for i in ['col1', 'col2']])
print (a)
0     True
1    False
2     True
dtype: bool

b = np.logical_or.reduce([kdf[i].str.contains('^\s*F', na=False) for i in ['col1', 'col2']])
print (b)
[ True False  True]

c = kdf['col1'].str.contains('^\s*F', na=False) | kdf['col2'].str.contains('^\s*F', na=False)
print (c)
0     True
1    False
2     True
dtype: bool