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

后端 未结 4 725
滥情空心
滥情空心 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:19

    you can use select_dtypes() including number dtype or excluding all columns of object and datetime64 dtypes:

    Demo:

    In [162]: df
    Out[162]:
      col1  col2  col3       date
    0    A     1    30 2016-01-01
    1    B     2    10 2016-01-02
    2    C     3    20 2016-01-03
    
    In [163]: df.dtypes
    Out[163]:
    col1            object
    col2             int64
    col3             int64
    date    datetime64[ns]
    dtype: object
    
    In [164]: df.select_dtypes(exclude=['object', 'datetime']) * 3
    Out[164]:
       col2  col3
    0     3    90
    1     6    30
    2     9    60
    

    or a much better solution (c) ayhan:

    df[df.select_dtypes(include=['number']).columns] *= 3
    

    From docs:

    To select all numeric types use the numpy dtype numpy.number

提交回复
热议问题