从一个大熊猫df到另一个大熊猫的平均行(使用两个键)

时间:2020-06-04 20:29:46

标签: python pandas dataframe

我有两个数据框。

DF1看起来像:

mock up of 4 column table, two id columns, two data columns representing averages

DF2看起来像:

mock up of 3 column table, two id columns, one data column representing raw values

我需要从DF2中找到Question_3的平均值,然后将其作为Question_3_Mean添加到与ID_1和ID_2匹配的适当行中。

mock up of 5 column table, two id columns, three data columns representing averages (third column is the average of the scores from DF2

我觉得这在Pandas中相对来说是微不足道的,但是我不确定要使用哪种命名法来找出方法。

我最初的工作是在Excel中创建一个新工作表,然后手动(使用公式)将两个ID组合在一起,然后使用数据透视表获取平均值,然后进行vlookup匹配结果。然后,我将其用作我的海图的df。

我想在Pandas中完成所有这一切,因为这种“匹配”是我经常要做的任务,并且我想省去手动步骤。

1 个答案:

答案 0 :(得分:0)

好像您可以先尝试groupby()然后尝试merge

df1.merge(df2.groupby(['ID_1','ID_2']).mean().add_suffix('_Mean'),
          on=['ID_1','ID_2'])