0
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.

aartist
  • 3,015
  • 3
  • 30
  • 30
  • See [Series.replace](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html) -> `df['B'] = df['A'].replace({1: 100, 2: 200})` – Henry Ecker Sep 02 '21 at 17:56

0 Answers0