首页 > 解决方案 > Pandas 通过正则表达式选择列并通过 if 更改其值,否则

问题描述

我有这样的熊猫数据框:

   a      b1         b2         b3       b4       c1      c2       c3         c4
   a1     0.10       0.0        0.21     0.0      0.03    0.10     0.04      0.0

如何将其更改为以下内容:

   a      b1         b2         b3       b4       c1      c2       c3         c4
   a1     1          0           1       0        1       0        1          0

所以,我想选择b*c*列并将任何非零值更改为 1,将任何零值更改为 0。因此,首先通过正则表达式选择列,然后在那里应用 if-else 规则。还值得注意的是,所有b*,c*列都是字符串 (obj) 类型。

我怎样才能做到这一点?

标签: python-3.xregexpandas

解决方案


正则表达式不是必需的,请str.startswith改用:

filter_col = [col for col in df if col.startswith('b') or col.startswith('c')]
df[filter_col] = (df[filter_col] > 0).astype(int)
print(df)

印刷:

    a  b1  b2  b3  b4  c1  c2  c3  c4
0  a1   1   0   1   0   1   1   1   0

编辑:如果你的“数字”最初是字符串,你可以这样做:

filter_col = [col for col in df if col.startswith('b') or col.startswith('c')]
df[filter_col] = (df[filter_col].astype(float) > 0).astype(int)
# if you want keep them as strings after computation:
# df[filter_col] = (df[filter_col].astype(float) > 0).astype(int).astype(str)
print(df)

推荐阅读