【问题标题】:Pandas select columns by regex and change their values by if, elsePandas 通过正则表达式选择列并通过 if 更改其值,否则
【发布时间】:2021-02-03 13:44:52
【问题描述】:

我有这样的 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)类型。

我该怎么做?

【问题讨论】:

    标签: python-3.x regex pandas


    【解决方案1】:

    不需要正则表达式,请改用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)
    

    【讨论】:

    • 嗨@Andrej Kesley,我想将列的原始数据类型保留为字符串。
    • @SumitSidana 为什么将数字存储为字符串?这里更广泛的背景是什么?
    • @SumitSidana 你的意思是数字01 应该是字符串而不是整数?
    • @AndrejKesely我得到TypeError: '>' not supported between instances of 'str' and 'int' 为您的解决方案。值得注意的是filter_col都是str类型。
    • @SumitSidana 我会在您的分析管道中尽可能长时间地将数字存储为数字,并在最后一步转换为字符串
    【解决方案2】:

    另一个选项是str.match:

    mask = df.columns.str.match('^(b|c)')
    df.loc[:, mask] = np.where(df.loc[:,mask].astype(float)==0, '0', '1')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      相关资源
      最近更新 更多