Python 在特定条件下合并两个数据帧

Python 在特定条件下合并两个数据帧,python,pandas,Python,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"], "na

我有两个熊猫数据帧,我想在特定条件下合并它们。这些是我的数据帧:

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
我希望从我的结果数据框中显示如下:

    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

所以我想在“name”列中合并它们,但我想删除nan值。如何才能做到这一点?

您可以使用
.merge
加入数据帧,并使用
.dropna
删除具有NA值的行

df1.merge(df2,how='left',on='name').dropna()
#返回:
食品名称颜色
0果苹果红
1果苹果绿
2果苹果黄
3果葡萄白
4果葡萄蓝

也可以与NaN共享一个示例,这样更容易理解您的意思。我的两个数据帧中没有NaN,我猜合并后会出现NaN,因为我没有所有值(“Bannana值”),您可以使用merge或concat,然后使用dropna