gpt4 book ai didi

python - np.logic_or 与reduce 返回不同的结果

转载 作者:行者123 更新时间:2023-12-01 07:10:45 25 4
gpt4 key购买 nike

np.ological_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.logic_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.ological_or(np.nan, True)返回True。我希望reduce将该函数应用于所有列表项,即

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

我错过了什么吗?

最佳答案

我认为这是错误,为了正确处理 NaNs 应该将它们替换为一些 boolean ,例如通过 na=False 参数设置为 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

关于python - np.logic_or 与reduce 返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58229604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com