【问题标题】:Set new column values in pandas DataFrame1 where DF2 column values match DF1 index在 Pandas DataFrame1 中设置新列值,其中 DF2 列值与 DF1 索引匹配
【发布时间】:2018-04-04 06:15:07
【问题描述】:

我想在 pandas 数据框中设置一个新列,其值使用 dataframe2 上的 groupby 计算得出。

DF1:

     col1    col2
id    
 1    'a'
 2    'b'
 3    'c'

DF2:

          id    col2
 index    
     1     1      11
     1     1      22
     1     1      12
     1     1      45
     3     3      83
     3     3      11
     3     3      35
     3     3      54

我想将 DF2 按 'id' 分组,然后在 'col2' 上应用一个函数,将结果放入 DF1 中的相应索引中。如果该特定索引没有组,那么我想用 NaN 填充...

ret_val = DF2.groupby('id').apply(lambda x: my_func(x['col_2']))

     col1    col2
id    
 1    'a'    ret_val
 2    'b'    NaN
 3    'c'    ret_val

...虽然我不知道如何实现这一点

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    首先在 df2 的 col2 上应用该函数,然后使用 pd.concat 在 df 中删除 col2,因为它是空的。

    x = df2.groupby('id')['col2'].apply(sum) # instead of sum use your own function
    ndf = pd.concat([df.drop('col2',1),x],1)
    
    col1 col2 ID 1'a' 90.0 2 'b' 南 3 'c' 183.0

    @Zero 建议的简单直接

    df1['col2'] = df2.groupby('id')['col2'].apply(sum)
    

    【讨论】:

    • 其实df1['col2'] = df2.groupby('id')['col2'].apply(sum) 就行了?
    【解决方案2】:

    您可以将sum 替换为.apply(lambda x : your_func(x))

    df1.col2=df.set_index('id').groupby(level='id').sum()
    df1
    Out[975]: 
       col1   col2
    id            
    1   'a'   90.0
    2   'b'    NaN
    3   'c'  183.0
    

    【讨论】:

    • df1.col2=df.groupby('id').sum() 应该怎么做?
    • @Zero 是的,你明白了,想多了……哈哈
    • 我也想太多了。 TBH @Zero 也想太多了哈哈
    【解决方案3】:

    df1.index 系列上使用map

    In [5327]: df1['col2'] = df1.index.to_series().map(df2.groupby('id')
                                                          .apply(lambda x: my_func(x['col2'])))
    
    In [5328]: df1
    Out[5328]:
       col1   col2
    id
    1     a  360.0
    2     b    NaN
    3     c  536.0
    

    详情

    In [5322]: def my_func(x):
          ...:     return x.sum()
          ...:
    
    In [5323]: df2.groupby('id').apply(lambda x: my_func(x['col2']))
    Out[5323]:
    id
    1    360.0
    3    536.0
    dtype: float64
    
    In [5324]: df1.index.to_series().map(df2.groupby('id').apply(lambda x: my_func(x['col2'])))
    Out[5324]:
    id
    1    360.0
    2      NaN
    3    536.0
    Name: id, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2020-09-08
      • 2018-08-06
      相关资源
      最近更新 更多