簡體   English   中英

Python Pandas:僅當列值唯一時,才將數據框追加到另一個數據框

[英]Python Pandas: Append Dataframe To Another Dataframe Only If Column Value is Unique

我有兩個要附加在一起的數據框。 以下是示例。

df_1:

Code    Title
103     general checks 
107     limits
421     horseshoe
319     scheduled 
501     zonal 

df_2

Code    Title
103     hello 
108     lucky eight 
421     little toe 
319     scheduled cat
503     new item 

我只想在df_1中不存在df_2中的代碼號的情況下,才將df_2附加到df_1。

以下是我想要的數據框:

Code    Title
103     general checks 
107     limits
421     horseshoe
319     scheduled 
501     zonal 
108     lucky eight 
503     new item

我已經搜索過Google和Stackoverflow,但是在這種情況下找不到任何東西。

只需append過濾的數據框

df3 = df2.loc[~df2.Code.isin(df.Code)]
df.append(df3)

    Code    Title
0   103 general checks
1   107 limits
2   421 horseshoe
3   319 scheduled
4   501 zonal
1   108 lucky eight
4   503 new item

請注意,您可能最終得到重復的索引,這可能會導致問題。 為避免這種情況,您可以.reset_index(drop=True)獲得沒有重復索引的新df。

df.append(df3).reset_index(drop=True)

    Code    Title
0   103 general checks
1   107 limits
2   421 horseshoe
3   319 scheduled
4   501 zonal
5   108 lucky eight
6   503 new item

您可以concat ,然后drop_duplicates 假設每個數據幀中的Code都是唯一的。

res = pd.concat([df1, df2]).drop_duplicates('Code')

print(res)

   Code           Title
0   103  general_checks
1   107          limits
2   421       horseshoe
3   319       scheduled
4   501           zonal
1   108     lucky_eight
4   503        new_item

與concat()類似,您也可以使用merge:

df3 = pd.merge(df_1, df_2, how='outer').drop_duplicates('Code')

    Code    Title
0   103 general checks
1   107 limits
2   421 horseshoe
3   319 scheduled
4   501 zonal
6   108 lucky eight
9   503 new item  

暫無
暫無

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

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