我想比较 2 个给定数据帧的所有行
如何优化以下代码以动态迭代给定 pandas 数据帧的所有列?
df1,df2 = pd.read_csv(...)
for index2, row2 in df2.iterrows():
for index1, row1 in df1.iterrows():
if row1[0]==row2[0]: i = i+1
if row1[1]==row2[1]: i = i+1
if row1[2]==row2[2]: i = i+1
if row1[3]==row2[3]: i = i+1
print("# same values: "+str(i))
i = 0
最佳答案
IIUC,您需要检查一个数据帧的整行是否等于另一个数据帧。您可以比较两个数据帧的相等性,然后使用 all
方法使用 axis=1
检查行,然后对结果求和:
df1 = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [2, 3, 4, 5, 6]})
df2 = pd.DataFrame({'a': [1, 5, 3, 7, 5], 'b': [2, 3, 8, 5, 6]})
In [1531]: df1 == df2
Out[1531]:
a b
0 True True
1 False True
2 True False
3 False True
4 True True
In [1532]: (df1 == df2).all(axis=1)
Out[1532]:
0 True
1 False
2 False
3 False
4 True
dtype: bool
In [1533]: (df1 == df2).all(axis=1).sum()
Out[1533]: 2
result = (df1 == df2).all(axis=1).sum()
In [1535]: print("# same values: "+str(result))
# same values: 2
关于python - 迭代所有数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34643500/