1

Lets say I have lots of columns, something in this format

  name1  val1 name2  val21  val22  ...
0     a     1    aa      1      5
1     b     2    bb      2      6
2     c     3    cc      3      7  

Any efficient / one-liner to do arithmetic(scalar) operations on only the numeric columns ?,
something like this

  df = df.mul(100)

  name1  val1 name2  val21  val22 ...
0     a   100    aa    100    500
1     b   200    bb    200    600
2     c   300    cc    300    700 
Julkar9
  • 1,508
  • 1
  • 12
  • 24
  • 3
    [pandas, multiply all the numeric values in the data frame by a constant](https://stackoverflow.com/q/38543263/15497888) and [Selecting Pandas Columns by dtype](https://stackoverflow.com/q/21271581/15497888) – Henry Ecker Sep 05 '21 at 16:10

1 Answers1

1

You can find the numeric columns using select_dtypes:

s = df.select_dtypes("number").columns
df[s] *= 100

print (df)

  name1  val1 name2  val21  val22
0     a   100    aa    100    500
1     b   200    bb    200    600
2     c   300    cc    300    700
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • 1
    `df[df.select_dtypes("number").columns] *= 100` @not_speshal From [this answer](https://stackoverflow.com/a/38543323/15497888) – Henry Ecker Sep 05 '21 at 16:11
  • Another way: `df.assign(**df._get_numeric_data()*100)` : `df.update` should work too – anky Sep 05 '21 at 16:16