簡體   English   中英

熊貓中兩個數據框之間的差異

[英]difference between two dataframes in Pandas

我試圖找到兩個數據框之間的差異,並且生成的df應該返回與第一個數據框匹配的行。 由於df2中不存在id的6,7,因此計數值保持不變。

我的兩個數據框

在此處輸入圖片說明

結果數據框:

在此處輸入圖片說明

使用subset_index為對齊DataFrame由s id列,添加reindex用於id只能由df1.id

df = (df1.set_index('id')
        .sub(df2.set_index('id'), fill_value=0)
        .reindex(df1['id'])
        .astype(int)
        .reset_index())
print (df)
   id  count
0   1      0
1   2      0
2   3      0
3   4      0
4   5      0
5   6      9
6   7      4

另一種解決方案是merge和左聯接,然后用pop減去count_ column來減去sub

df = df1.merge(df2, on='id', how='left', suffixes=('','_'))
df['count'] = df['count'].sub(df.pop('count_'), fill_value=0).astype(int)
print (df)
   id  count
0   1      0
1   2      0
2   3      0
3   4      0
4   5      0
5   6      9
6   7      4

設置

df1 = pd.DataFrame({'id':[1,2,3,4,5,6,7],
                    'count':[3,5,6,7,2,9,4]})

print (df1)
   id  count
0   1      3
1   2      5
2   3      6
3   4      7
4   5      2
5   6      9
6   7      4

df2 = pd.DataFrame({'id':[1,2,3,4,5,8,9],
                    'count':[3,5,6,7,2,4,2]})

print (df2)
   id  count
0   1      3
1   2      5
2   3      6
3   4      7
4   5      2
5   8      4
6   9      2

采用:

temp = pd.merge(df1, df2, how='left', on='id').fillna(0)
temp['count'] = temp['count_x'] - temp['count_y']
temp[['id', 'count']]

   id  count
0   1    0.0
1   2    0.0
2   3    0.0
3   4    0.0
4   5    0.0
5   6    9.0
6   7    4.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM