pandas, multiply all the numeric values in the data frame by a constant

后端 未结 4 738
滥情空心
滥情空心 2021-01-01 17:37

How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:

In [13]: df = pd.DataFrame         


        
4条回答
  •  误落风尘
    2021-01-01 18:16

    One way would be to get the dtypes, match them against object and datetime dtypes and exclude them with a mask, like so -

    df.ix[:,~np.in1d(df.dtypes,['object','datetime'])] *= 3
    

    Sample run -

    In [273]: df
    Out[273]: 
      col1  col2  col3
    0    A     1    30
    1    B     2    10
    2    C     3    20
    
    In [274]: df.ix[:,~np.in1d(df.dtypes,['object','datetime'])] *= 3
    
    In [275]: df
    Out[275]: 
      col1  col2  col3
    0    A     3    90
    1    B     6    30
    2    C     9    60
    

提交回复
热议问题