[英]Merging two data frames and keeping the extra rows from first df
I have 2 data frames df1 and df2我有 2 个数据框 df1 和 df2
df1 df1
A B
id0 a 3
id1 b 4
id2 c 0
df2 df2
A B
id2 aa 80
id3 d 44
id4 r 100
I want to join concat df1 and df2 in such a way that all rows of df1 are retained and if there are rows with the same index in df2( id2 ; in this case );我想以这样的方式连接 concat df1 和 df2,即保留 df1 的所有行,并且如果 df2( id2 ;在这种情况下) 中存在具有相同索引的行; its dropped from df2.
它从 df2 下降。
Final df should look like最终 df 应该看起来像
A B
id0 a 3
id1 b 4
id2 c 0
id3 d 44
id4 r 100
How can it be done in pandas python?如何在 Pandas python 中完成?
Regards问候
You can use combine_first
, it is specifically designed for this operation:您可以使用
combine_first
,它是专门为此操作设计的:
df1.combine_first(df2)
output:输出:
A B
id0 a 3
id1 b 4
id2 c 0
id3 d 44
id4 r 100
Use concat
with filter first duplicates by Index.duplicated
:使用
concat
和按Index.duplicated
过滤第一个重复Index.duplicated
:
df = pd.concat([df1, df2])
df = df[~df.index.duplicated()]
print (df)
A B
id0 a 3
id1 b 4
id2 c 0
id3 d 44
id4 r 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.