pandas ,将数据框中的所有数值乘以一个常数 [英] pandas, multiply all the numeric values in the data frame by a constant

查看:235
本文介绍了 pandas ,将数据框中的所有数值乘以一个常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数据框中的所有数值乘以一个常数,而不必显式指定列名?示例:

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({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]})

In [14]: df
Out[14]: 
  col1  col2  col3
0    A     1    30
1    B     2    10
2    C     3    20

我尝试了 df.multiply ,但它也会多次连接字符串,从而影响字符串值。

I tried df.multiply but it affects the string values as well by concatenating them several times.

In [15]: df.multiply(3)
Out[15]: 
  col1  col2  col3
0  AAA     3    90
1  BBB     6    30
2  CCC     9    60

有没有办法在仅将数字值乘以常数的同时保留字符串值的完整性?

Is there a way to preserve the string values intact while multiplying only the numeric values by a constant?

推荐答案

您可以使用 select_dtypes()包括 number dtype或排除对象的所有列 datetime64 dtypes:

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

或更好的解决方案(c) ayhan

or a much better solution (c) ayhan:

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

来自文档


要选择所有数字类型,请使用numpy dtype numpy.number

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

这篇关于 pandas ,将数据框中的所有数值乘以一个常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆