【问题标题】:Pandas DataFrame update and sum by matching multi-column index from another Pandas Series通过匹配来自另一个 Pandas 系列的多列索引来更新和求和 Pandas DataFrame
【发布时间】:2021-08-09 12:55:54
【问题描述】:

我有

df =

     B     TF    C   N
0  356   True  714   1
1  357   True  718   2
2  358   True  722   3
3  359   True  726   4
4  360  False  730   5

lt =

 B    C  
356  714    223
360  730    101
400  800    200
Name: N, dtype: int64

type(lt) => pandas.core.series.Series

我喜欢将系列lt 视为多列查找表

因此,如果数据帧中的键 B 和 C 恰好在系列索引中找到,我希望通过对 N 的相应值求和来更新数据帧。

所以我的最终数据框应该是这样的:

       B     TF    C  N
0    356   True  714  224
1    357   True  718  2
2    358   True  722  3
3    359   True  726  4
4    360  False  730  106

我应该怎么做? 我尝试了各种选项,例如:

df['N'] = df['N'] + df.apply(lambda x:lt[x[['B','C']]],axis=1)

但它给出了:

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

还有:

df.apply(lambda x:lt[x.B,x.C],axis=1)

提高KeyError (357, 718)

我应该怎么做? 谢谢。

【问题讨论】:

  • 您能否提供熊猫对象作为代码:df.to_dict()
  • { 'B': {0: 356, 1: 357, 2: 358, 3: 359, 4: 360}, 'TF': {0: 'True', 1: 'True ', 2: '真', 3: '真', 4: '假'}, 'C': {0: 714, 1: 718, 2: 722, 3: 726, 4: 730}, 'N' : {0:1, 1:2, 2:3, 3:4, 4:5}}

标签: python pandas dataframe merge


【解决方案1】:

你的方法很接近。只需要微调将列的值对B 和C 映射到lt 的索引的方式。详情见下文:

你可以使用.apply() + .map() + fillna(),如下:

在映射lt之前将列B&C的值对变成元组,这样就可以从lt获取映射值。对于不在lt 中的值,我们将fillna(0) 设置为默认0:

df['N'] =  df['N'] + df[['B', 'C']].apply(tuple, axis=1).map(lt).fillna(0, downcast='infer')

结果:

print(df)


     B     TF    C    N
0  356   True  714  224
1  357   True  718    2
2  358   True  722    3
3  359   True  726    4
4  360  False  730  106

【讨论】:

    【解决方案2】:

    使用merge 和eval:

    out = df.merge(lt.reset_index(), on=['B', 'C'], how='left') \
            .fillna(0).eval('N = N_x + N_y') \
            .drop(columns=['N_x', 'N_y'])
    
    >>> out
         B     TF    C      N
    0  356   True  714  224.0
    1  357   True  718    2.0
    2  358   True  722    3.0
    3  359   True  726    4.0
    4  360  False  730  106.0
    

    【讨论】:

    • 删除了不必要的列“A”。
    • 如您所愿吗?
    • 是的 Corralien。你的回答是绝对正确的,我以类似的方式接近,不止一个陈述。我试图在 Data Frame 中不添加额外的列。
    猜你喜欢
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多