python-3.x - Pandas 通过正则表达式选择列,并通过 if、else 更改它们的值

标签 python-3.x regex pandas

我有这样的 Pandas 数据框:

   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) 类型。

我该怎么做?

最佳答案

正则表达式不是必需的,请使用 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)

关于python-3.x - Pandas 通过正则表达式选择列,并通过 if、else 更改它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64450095/

相关文章:

python - 无法在 zsh 上安装 python 包,但在 bash 上安装成功

python - 与 pytest 并行运行单元测试?

python - 如何在Python中用空值初始化一个对象?

regex - 如何删除非 ascii 字符并在非 ascii 字符使用 Perl 单行符的字段中附加一个空格?

regex - 如何使用单行解析需要多个匹配项的 csv 输出?

python - 隔离林需要拆分数据吗?

python - 根据当前数据帧中的约束生成数据帧列

python - 将列表的一部分与Python中的完整列表进行比较

javascript 正则表达式 短信字符数

python - 计算整个 Pandas DataFrame 的出现次数