[英]how to iterate each row of one dataframe and compare with rows in another dataframe in Python?
[英]Compare each row in one dataframe to each row in another dataframe in Python
我有兩個具有相同功能的不同數據框。
df1
AGE Country Income
-----------------------
33 UK 3500
24 Australia 1500
df2
AGE Country Income
-----------------------
33 Brazil 1300
54 Australia 2230
我想將 df1 中的每一行與每一行 df2 進行比較,並計算在特征值中發現的差異數。
在我的示例中,我們有 2 個數據幀,每個數據幀有 2 個實例。 所以,會有4種比較。
對於每次比較,我需要返回特征差異的數量。 例如,如果我們將 df1 中的第一行與 df2 中的第一行進行比較,我們將在特征值上有 2 個差異。
知道如何實現嗎?
如果我理解正確,一種方法是使用np.where()
並為每個特征單獨計算每行的差異數並對這些數組求和:
arr = np.where(df_1['Age']!=df_2['Age'],1,0) + np.where(df_1['Country'] != df_2['Country'],1,0) + np.where(df_1['Income']!=df_2['Income'],1,0)
這將返回一個數組,其中包含每行的特征差異數。 在這種情況下,輸出將是:
[2,2]
如果有很多列,如下例所示,您可以使用 for 循環:
df_1 = pd.DataFrame({'Age':[1,2,3,4],'Country':['Brazil','UK','Australia','China'],'Var_x':[7,5,7,7],'Var_y':[3,6,3,2],'Var_z':[20,32,31,34]})
df_2 = pd.DataFrame({'Age':[1,2,4,5],'Country':['Egypt','UK','India','China'],'Var_x':[7,4,3,7],'Var_y':[3,6,2,2],'Var_z':[20,32,4,32]})
differences = np.zeros(len(df_1))
for i in df_1:
differences += np.where(df_1[i]!=df_2[i],1,0)
print(differences)
輸出:
[1. 1. 5. 2.]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.