[英]How two panda data frames with same column values can be merged to form the third data frame that shows the difference of the values
數據框:DF1
name age id salary
0 Smith 30 2 2000
1 Ron 24 3 30000
2 Mike 35 4 40000
3 Jack 21 5 5000
4 Roshan 20 6 60000
5 Steve 45 8 8000
6 Peter 32 1 1000
數據框:DF2
name age salary id
0 Peter 28 10000 1
1 Smith 30 1500 2
2 Ron 24 7000 3
3 Mike 35 20000 4
4 Jack 21 5000 5
5 Cathy 20 9000 6
6 Steve 45 56000 8
df1和df2要在ID上合並。請不要讓df1和df2中的ID相同,但ID順序不同。df3需要如下創建:
name age id salary
0 Smith 30 2 2000|1500
1 Ron 24 3 30000|7000
2 Mike 35 4 40000 |20000
3 Jack 21 5 5000
4 Roshan|Cathy 20 6 60000|9000
5 Steve 45 8 8000|56000
6 Peter 32|28 1 1000|10000
我打算使用to_excel功能將上述輸出放到excel工作表中。 在此之前,我想在此數據幀中再添加一列,即“匹配和不匹配”。 邏輯上,如果顯示最小一個差值結果的行中的任何一個應該不匹配否則匹配。我正在模擬這樣的輸出-
id年齡名稱薪水結果0 2 30 Smith 2000 | 1500不匹配1 3 24 Ron 30000 | 7000不匹配3 5 21 Jack 5000匹配4 6 20 Roshan | Cathy 60000 | 9000不匹配5 5 45 Steve 8000 | 56000不匹配6 1 32 | 28彼得1000 | 10000錯誤配對
我可以用什么來達到這樣的結果
首先使用merge
,然后按條件與numpy.where
列,最后按df1.columns
僅過濾列:
cols = df1.columns.difference(['id'])
df = df1.merge(df2, on='id', suffixes=('','_'))
s = df[cols].astype(str) + '|' + df[cols + '_'].astype(str).values
mask = df[cols].values != df[cols + '_'].values
arr = np.where(mask, s, df[cols].astype(str))
df = df1[['id']].join(pd.DataFrame(arr, columns=cols))
print (df)
id age name salary
0 2 30 Smith 2000|1500
1 3 24 Ron 30000|7000
2 4 35 Mike 40000|20000
3 5 21 Jack 5000
4 6 20 Roshan|Cathy 60000|9000
5 8 45 Steve 8000|56000
6 1 32|28 Peter 1000|10000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.