首页 > 解决方案 > Applying pandas map without function

问题描述

df = pd.DataFrame({ 'A': [1,2,3,4],
                    'B': [10,20,30,40],
                    'C': [20,40,60,80]
                  },
                  index=['Row1', 'Row2', 'Row3', 'Row4'])

def mapping(row):
    amap = { 1: 100, 2:200}
    if row.A in amap.keys(): row.B = amap[row.A]
    return row

df.apply(mapping,axis=1)
print(df)
Above code works.
      A    B   C
Row1  1  100  20
Row2  2  200  40
Row3  3   30  60
Row4  4   40  80

Is there a shorter version, especially without using function? Is it worth it? Thanks.

标签: pythonpandas

解决方案


推荐阅读