![](/img/trans.png)
[英]Iterate through two data frames and update a column of the first data frame with a column of the second data frame in pandas
[英]Calculating difference of two data frames for each column of first data frame
假設我有兩個數據框:
df1:4 列,n 行
df2:50 列,n 行
計算 df1 的每一列與 df2 的所有列的差異的最佳方法是什么?
到目前為止,我唯一的想法是合並表並創建具有差異的 4*50 新列,作為一個循環。 但必須有更好的方法,對吧?
已經謝謝了! 保羅
為此,我創建了 2 個虛構的數據框:
輸入數據框
df1 = pd.DataFrame({"a":[1,1,1],
"b":[2,2,2],
})
df2 = pd.DataFrame({"aa":[10,10,10],
"bb":[20,20,20],
"cc":[30,30,30],
"dd":[40,40,40],
"ee":[50,50,50]
})
print(df1)
a b
0 1 2
1 1 2
2 1 2
print(df2)
aa bb cc dd ee
0 10 20 30 40 50
1 10 20 30 40 50
2 10 20 30 40 50
解決方案
df = pd.concat([df2.sub(df1[i], axis=0) for i in df1.columns],axis =1)
df.columns= [i for i in range(df1.shape[1]*df2.shape[1])]
df
結果
0 1 2 3 4 5 6 7 8 9
0 9 19 29 39 49 8 18 28 38 48
1 9 19 29 39 49 8 18 28 38 48
2 9 19 29 39 49 8 18 28 38 48
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.