[英]Pandas Add New Columns Based on Vaues from Different DataFrame
我有下面的dataframe,姑且稱之為df1
id level a b c d
1 One 1 3 4 4
1 two 1 3 4
2 One 1 3 4 4
2 two 1 3 4
然后,還有第二個 dataframe,df2。
id Type Value
1 a 11
1 b 22
1 c 33
1 d 44
2 a 91
2 b 92
2 c 93
2 d 94
我想要比較 df1 和 df2 的值以添加新列,如下所示。 添加名為type
_ s
新列,其值來自 df2。
id level a b c d a_s b_s c_s d_s
1 One 1 3 4 4 11 22 33 44
1 two 1 3 4 11 22 33 44
2 One 1 3 4 4 91 92 93 94
2 two 1 3 4 91 92 93 94
堆疊、取消堆疊 df2 並與 df 合並
pd.merge(df,df2.set_index(['id','Type']).stack().unstack('Type').reset_index().drop(columns=['level_1']), how='left',on='id',suffixes=('', '_s'))
id level a b c d a_s b_s c_s d_s
0 1 One 1 3 4 4.0 11 22 33 44
1 1 two 1 3 4 NaN 11 22 33 44
2 2 One 1 3 4 4.0 91 92 93 94
3 2 two 1 3 4 NaN 91 92 93 94
或 pivot df2 並合並
pd.merge(df,pd.pivot(df2, index='id', columns='Type').droplevel(0, axis=1).reset_index(), how='left',on='id',suffixes=('', '_s'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.