【问题标题】:How to merge two dataframes but one dataframe has more than one cell with the condition?如何合并两个数据框但一个数据框有多个具有条件的单元格?
【发布时间】:2021-07-31 16:38:50
【问题描述】:

假设我们有两个数据框:

    df1 = pd.DataFrame(
        [["foo",10], ["bar",20]], 
        columns=["1", "2"], 
        index=["x", "y"]
    )
    df2 = pd.DataFrame(
        [["foo",10,20], ["bar",20,30], ["foo",10,30]],
        columns=["1", "2", "3"],
        index=["x", "y", "z"]
    )

这会给我们这个:

output of df1 & df2

如果我要将这些数据与两列上的条件合并:

df3 = pd.merge(df1, df2, how='left', on=['1','2'])

这会给我们这个:

output of merged df3

如果我希望将与 df2 中的条件匹配的值的平均值输出到 df3,我该怎么做呢? (因此,我不会有两行 foo & 10,而是只有一行 foo & 10,第三列的值是符合条件的两行的平均值)。为了清楚起见,我在下面提供了一张图片:

wanted output of merged df3

【问题讨论】:

  • 你的合并是什么意思?

标签: python pandas dataframe join merge


【解决方案1】:

如果你想刻薄,那就试试吧:

df2 = df2.groupby(['1','2'], as_index=False).mean()
df3 = pd.merge(df1, df2, how='left', on=['1','2'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 2018-03-15
    • 2018-07-16
    • 2021-12-04
    • 2023-04-10
    • 2021-03-30
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多