pandas 使用正则表达式选择列并除以值 [英] Pandas select columns with regex and divide by value

查看:125
本文介绍了 pandas 使用正则表达式选择列并除以值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将与正则表达式匹配的某些列中的所有值除以某个值,并且仍然具有完整的数据框.

I want to divide all values in certain columns matching a regex expression by some value and still have the complete dataframe.

可在此处找到:如何通过以下方式从数据框中选择列正则表达式,例如可以从d开头的所有列中进行选择:

As can be found here: How to select columns from dataframe by regex , e.g. all columns starting with d can be selected with:

df.filter(regex=("d.*"))

现在我已经选择了需要的列,例如将值除以2.这可以通过以下代码完成:

Now I have the columns selected I need, I want e.g. divide the values by 2. Which is possible with the following code:

df.filter(regex=("d.*")).divide(2)

但是,如果我尝试像这样更新数据框,则会显示can't assign to function call:

However if I try to update my dataframe like this, it gives a can't assign to function call:

df.filter(regex=("d.*")) = df.filter(regex=("d.*")).divide(2)

如何正确更新现有的df?

How to properly update my existing df?

推荐答案

以下技术不仅限于与过滤器配合使用,而且可以更广泛地应用.

The following technique is not limited to use with filter and can be applied far more generally.

设置
我将使用@cᴏʟᴅsᴘᴇᴇᴅ设置
df为:

Setup
I'll use @cᴏʟᴅsᴘᴇᴇᴅ setup
Let df be:

   d1  d2  abc
0   5   1    8
1  13   8    6
2   9   4    7
3   9  16   15
4   1  20    9


就地更新
使用 pd.DataFrame.update
update将采用参数数据框,并在索引和列值与参数匹配的地方更改调用数据框.


Inplace update
Use pd.DataFrame.update
update will take the argument dataframe and alter the calling dataframe where index and column values match the argument.

df.update(df.filter(regex='d.*') / 3)
df

         d1        d2  abc
0  1.666667  0.333333    8
1  4.333333  2.666667    6
2  3.000000  1.333333    7
3  3.000000  5.333333   15
4  0.333333  6.666667    9


内联副本
使用
pd.DataFrame.assign
我使用双splat **将参数数据框解压缩到字典中,其中列名是键,而列的序列是值.这与assign的必需签名相匹配,并覆盖生成的副本中的那些列.简而言之,这是调用数据帧的副本,其中的列已被适当覆盖.


Inline copy
Use pd.DataFrame.assign
I use the double splat ** to unpack the argument dataframe into a dictionary where column names are keys and the series that are the columns are the values. This matches the required signature for assign and overwrites those columns in the copy that is produced. In short, this is a copy of the calling dataframe with the columns overwritten appropriately.

df.assign(**df.filter(regex='d.*').div(3))

         d1        d2  abc
0  1.666667  0.333333    8
1  4.333333  2.666667    6
2  3.000000  1.333333    7
3  3.000000  5.333333   15
4  0.333333  6.666667    9

这篇关于 pandas 使用正则表达式选择列并除以值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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