2

I have a dataframe df with multiple columns and I want to apply the same logic to multiple columns at once. I know how to do it for one column at a time but anyone has an idea how to apply the same logic for multiple columns in a single go?

dataframe df

col0  col1  col2  col3  col4  col5  col6  new_col
row0  24.0    83  42.0     7    96     0   NaN      192
row1  40.0     4   NaN    12    84     0   NaN      168
row2  83.0    22  80.0    26    15     0   NaN       30
row3  92.0    73  58.0     0    33     0   NaN       66
row4   NaN    63  35.0    70    95     0   NaN      190

I have to apply some transformation to col4, col5, col6. I am able to do it one by one but how to do it for all the columns at once in a single go?

df['col4'] = df['col4'].apply(lambda n: n*2)
df['col5'] = df['col5'].apply(lambda n: n*2)
df['col6'] = df['col6'].apply(lambda n: n*2)

1 Answers1

3

It depends of logic. If possible working with all columns like filtered DataFrame use:

cols = ['col4','col5','col6']

df[cols] = df[cols] * 2

#short version
df[cols] *= 2

If need complicated function and need working with each cell elementwise use DataFrame.applymap:

cols = ['col4','col5','col6']
df[cols] = df[cols].applymap(func)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252