Pandas选择带有正则表达式的列并除以值

时间:2018-01-15 07:19:06

标签: python regex pandas

我想将符合正则表达式的某些列中的所有值除以某个值,并且仍然具有完整的数据帧。

可在此处找到:How to select columns from dataframe by regex,例如所有以d开头的列都可以选择:

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

现在我选择了我需要的列,我希望例如将值除以2.可以使用以下代码:

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

但是,如果我尝试像这样更新我的数据框,它会提供can't assign to function call

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

如何正确更新我现有的df?

3 个答案:

答案 0 :(得分:11)

以下技术不限于与滤波器一起使用,并且可以更广泛地应用。

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

   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将获取参数dataframe并更改索引和列值与参数匹配的调用数据帧。

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所需的签名匹配,并覆盖生成的副本中的那些列。简而言之,这是调用数据帧的副本,其中列被适当地覆盖。

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

答案 1 :(得分:9)

我认为您需要提取列名称并指定:

01-15 11:03:22.593 3468-3468/com.example.oct30th D/MESSAGE: Message to be encrypted 1
01-15 11:03:22.593 3468-3468/com.example.oct30th D/n: 1291588321
01-15 11:03:22.593 3468-3468/com.example.oct30th D/nsquared: 1668200390943599041
01-15 11:03:22.594 3468-3468/com.example.oct30th D/RandomZStarN: 75325222
01-15 11:03:22.594 3468-3468/com.example.oct30th D/gmi: 1578485334874745

或者:

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

答案 2 :(得分:8)

使用c = df.columns.str.startswith('d') df.loc[:, c] /= 2

df

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

c = df.columns.str.startswith('d')  
c
array([ True,  True, False], dtype=bool)

df.loc[:, c] /= 3    # 3 instead of 2, just for example
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

举个例子,考虑一下 -

str.contains

如果您需要传递正则表达式,请使用c = df.columns.str.contains(p) # p => your pattern -

0 7 * * 1 program/bin/env -e ${ENVIRONMENT_ALIAS} ${ENVIRONMENT_ROOT}/bin/pop.py

其余代码如下。