【问题标题】:how to update a dataframe with another filtered dataframe如何用另一个过滤的数据框更新数据框
【发布时间】:2019-10-01 09:22:47
【问题描述】:

我有 2 个数据框。我需要用第二个中的平均值更新第一个中的一列,按索引分组。 这是一个例子 df1 (col1 是索引)

      col2 col3
col1           
a        0    X
b        0    0
c        0    0
d        0    0

df2(col1 是索引)

    col2  col3
col1            
a        1     0
a        3     0
d        2     0
d        4     0

我需要 df2 的 col2 (a=2, d=3) 的平均值,并且只为 col3 = X 的行更新 df1

我试过了

df1.loc[df1.col3=='X'].update(df2.groupby(df2.index),'col2'].mean().to_frame())

只有在我不使用 loc 时才有效。

我想要的结果 df1 (col1 是索引)

    col2 col3
col1           
a        2    X
b        0    0
c        0    0
d        0    0

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    用途:

    m=df2.groupby(df2.index).col2.mean()
    df1.loc[df1.col3=='X','col2']=m
    print(df1)
    

          col2 col3
    col1           
    a        2    X
    b        0    0
    c        0    0
    d        0    0
    

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 1970-01-01
      • 2018-03-08
      • 2023-03-12
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 2021-06-19
      相关资源
      最近更新 更多