問題描述
我想將兩個數(shù)據(jù)幀 A、B 連接到一個沒有重復行的新數(shù)據(jù)幀(如果 B 中的行已經(jīng)存在于 A 中,則不要添加):
I'd like to concatenate two dataframes A, B to a new one without duplicate rows (if rows in B already exist in A, don't add):
數(shù)據(jù)框 A:數(shù)據(jù)框 B:
Dataframe A: Dataframe B:
I II I II
0 1 2 5 6
1 3 1 3 1
新數(shù)據(jù)框:
I II
0 1 2
1 3 1
2 5 6
我該怎么做?
推薦答案
最簡單的方法是只進行連接,然后刪除重復項.
The simplest way is to just do the concatenation, and then drop duplicates.
>>> df1
A B
0 1 2
1 3 1
>>> df2
A B
0 5 6
1 3 1
>>> pandas.concat([df1,df2]).drop_duplicates().reset_index(drop=True)
A B
0 1 2
1 3 1
2 5 6
reset_index(drop=True)
是修復concat()
和drop_duplicates()
之后的索引.沒有它,您將擁有 [0,1,0]
的索引,而不是 [0,1,2]
.如果不立即重置,這可能會導致對該 dataframe
的進一步操作出現(xiàn)問題.
The reset_index(drop=True)
is to fix up the index after the concat()
and drop_duplicates()
. Without it you will have an index of [0,1,0]
instead of [0,1,2]
. This could cause problems for further operations on this dataframe
down the road if it isn't reset right away.
這篇關于Pandas/Python:如何連接兩個沒有重復的數(shù)據(jù)幀?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!