![](/img/trans.png)
[英]How to update the empty dataframe values with values from another dataframe(Pandas)?
[英]How to update one dataframe using values from another dataframe in pandas
我有兩個df
, df1
就像,
primary_key code amount
220492763 763 32.41
213274768 764 23.41
226835769 766 88.41
224874836 7766 100.31
219074759 74836 111.33
df2
就像
primary_key code amount
213274768 764 24.41
224874836 7766 101.31
217774816 768 123.43
222176762 798 111.44
219374759 24774 134.56
我喜歡使用df2
來基於相同的primary_key
更新df_1
,對於df2
的其余行,請將它們附加到df1
的末尾,所以結果看起來像是,
primary_key code amount
220492763 763 32.41
213274768 764 24.41
226835769 766 88.41
224874836 7766 101.31
219074759 74836 111.33
217774816 768 123.43
222176762 798 111.44
219374759 24774 134.56
嘗試使用
df1.set_index('primary_key').combine_first(df2.set_index('primary_key')).reset_index()
但是兩個df
混合在一起,我想知道如何解決它。
使用combine_first
yourdf=df2.set_index('primary_key').combine_first(df1.set_index('primary_key')).reset_index()
yourdf
Out[287]:
primary_key code amount
0 213274768 764.0 24.41
1 217774816 768.0 123.43
2 219074759 74836.0 111.33
3 219374759 24774.0 134.56
4 220492763 763.0 32.41
5 222176762 798.0 111.44
6 224874836 7766.0 101.31
7 226835769 766.0 88.41
更新添加訂單
idx=pd.concat([df1.primary_key,df2.primary_key]).drop_duplicates()
yourdf=df2.set_index('primary_key').combine_first(df1.set_index('primary_key')).reindex(idx).reset_index()
yourdf
Out[293]:
primary_key code amount
0 220492763 763.0 32.41
1 213274768 764.0 24.41
2 226835769 766.0 88.41
3 224874836 7766.0 101.31
4 219074759 74836.0 111.33
5 217774816 768.0 123.43
6 222176762 798.0 111.44
7 219374759 24774.0 134.56
使用pd.concat
, drop_duplicates
和reindex
:
idx=pd.concat([df1.primary_key,df2.primary_key]).drop_duplicates()
pd.concat([df2,df1]).drop_duplicates('primary_key').set_index('primary_key').reindex(idx).reset_index()
輸出:
primary_key code amount
0 220492763 763 32.41
1 213274768 764 24.41
2 226835769 766 88.41
3 224874836 7766 101.31
4 219074759 74836 111.33
5 217774816 768 123.43
6 222176762 798 111.44
7 219374759 24774 134.56
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.