【发布时间】:2020-11-27 23:56:10
【问题描述】:
我正在尝试使用两个数据框进行简单的 Pandas 查找。我有一个主要的主数据框(左)和一个查找数据框(右)。我想在匹配的整数代码上加入它们并从item_df 返回项目title。
我看到了一个带有键值对想法的轻微解决方案,但它看起来很麻烦。我的想法是使用col3 和name 作为关键列将merge 数据帧一起使用,并将value 保留在我想要的正确帧中,即title。因此我决定drop 我加入的key 列,所以我剩下的就是value。现在假设我想用我自己的手动命名约定多次执行此操作。为此,我使用rename 重命名我合并的值。现在我将重复此合并操作并将我的下一个连接重命名为second_title 之类的名称(参见下面的示例)。
是否有一种不那么繁琐的方法来执行这种重复操作,而无需不断删除合并的额外列并在每个合并步骤之间重命名新列?
示例代码如下:
import pandas as pd
master_dict: dict = {'col1': [3,4,8,10], 'col2': [5,6,9,10], 'col3': [50,55,59,60]}
master_df: pd.DataFrame = pd.DataFrame(master_dict)
item_dict: dict = {'name': [55,59,50,5,6,7], 'title': ['p1','p2','p3','p4','p5','p6']}
item_df: pd.DataFrame = pd.DataFrame(item_dict)
print(master_df.head())
col1 col2 col3
0 3 5 50
1 4 6 55
2 8 9 59
3 10 10 60
print(item_df.head())
name title
0 55 p1
1 59 p2
2 50 p3
3 5 p4
4 6 p5
# merge on col3 and name
combined_df = pd.merge(master_df, item_df, how = 'left', left_on = 'col3', right_on = 'name')
# rename title to "first_title"
combined_df.rename(columns = {'title':'first_title'}, inplace = True)
combined_df.drop(columns = ['name'], inplace = True) # remove 'name' column that was joined in from right frame
# repeat operation for "second_title"
combined_df = pd.merge(combined_df, item_df, how = 'left', left_on = 'col2', right_on = 'name')
combined_df.rename(columns = {'title': 'second_title'}, inplace = True)
combined_df.drop(columns = ['name'], inplace = True)
print(combined_df.head())
col1 col2 col3 first_title second_title
0 3 5 50 p3 p4
1 4 6 55 p1 p5
2 8 9 59 p2 NaN
3 10 10 60 NaN NaN
【问题讨论】:
标签: python pandas dataframe join merge