我有一个包含两列包含 float 的数据框。我首先排除列包含零的行,然后想要检查每一行,如果列的元素相等。
我尝试过:
df.loc[(df['col1'] != 0.0) & (df['col2'] != 0.0), 'Error'] = np.where(assert_almost_equal(df['col1'], df['col2']), 'Not equal', '')
结果是:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
还尝试过:
np.where(df['col1'] == df['col2'], 'Not equal', '')
和
np.where(df.col1.eq(df.col2), 'Not equal', '')
结果是:
ValueError: shape mismatch: value array of shape (24788,) could not be broadcast to indexing result of shape (9576,)
还尝试了apply
-function。
如何逐行比较两列中的 float ?我确实想要需要平等,而不是 isclose
或类似的东西。
谢谢,
马莫
最佳答案
我认为需要将所有掩码链接在一起以获得相同大小的 bool 掩码和DataFrame
以避免形状不匹配值错误
并且不改变DataFrame
的原始大小:
df = pd.DataFrame({'col1':[0,5,4,5.7,5,4],
'col2':[0,0,9,5.7,2,3],
'col3':[1,3,5,7,1,0]})
#print (df)
mask=(df['col1'] != 0.0) & (df['col2'] != 0.0) & (df['col1'] == df['col2'])
df['Error'] = np.where(mask, 'Equal', 'Not equal')
print (df)
col1 col2 col3 Error
0 0.0 0.0 1 Not equal
1 5.0 0.0 3 Not equal
2 4.0 9.0 5 Not equal
3 5.7 5.7 7 Equal
4 5.0 2.0 1 Not equal
5 4.0 3.0 0 Not equal
关于python - 检查 python 中浮点列的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616424/