簡體   English   中英

在特定條件下合並兩個 Pandas DataFrame

[英]Merging two Pandas DataFrames on specific condition

我有兩個 Pandas 數據框,我想在特定條件下合並它們。 這些是我的數據框:

import pandas as pd

pd.set_option('display.max_rows', 250)
pd.set_option('display.max_columns', 7)
pd.set_option('display.width', 800)


df1 = pd.DataFrame({"food":["fruit", "fruit", "fruit"],
                    "name":["apple", "grape", "bannana"]})
print(df1)


df2 = pd.DataFrame({"name":["apple", "apple", "apple", "grape", "grape"],
                    "color":["red", "green", "yellow","white", "blue"]})
print(df2)

它們看起來像這樣:

    food     name
0  fruit    apple
1  fruit    grape
2  fruit  bannana

    name   color
0  apple     red
1  apple   green
2  apple  yellow
3  grape   white
4  grape    blue

我希望我的結果數據框看起來像這樣:

    food   name   color
0  fruit  apple     red
1  fruit  apple   green
2  fruit  apple  yellow
3  fruit  grape   white
4  fruit  grape    blue

所以我想將它們合並到“名稱”列中,但我想刪除 nan 值。 我怎樣才能做到這一點?

您可以使用.merge加入數據框,並使用.dropna刪除具有 NA 值的行。

df1.merge(df2, how='left', on='name').dropna()
# returns:
    food   name   color
0  fruit  apple     red
1  fruit  apple   green
2  fruit  apple  yellow
3  fruit  grape   white
4  fruit  grape    blue

暫無
暫無

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

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