【问题标题】:Separating columns based on Regex | Pandas基于正则表达式分离列 |熊猫
【发布时间】:2020-11-14 17:32:47
【问题描述】:

所以我已将 pdf 转换为数据框,并且几乎处于我希望格式的最后阶段。但是我被困在以下步骤中。我有一列就像 -

Column A
1234[321]
321[3]
123
456[456]

并希望将其分成两个不同的列 B 和 C,这样 -

Column B          Column C
1234              321
321               3
123               0
456               456

如何做到这一点?我确实尝试过

df.Column A.str.strip(r"\[\d+\]")

但是在尝试了不同的变体之后我一直无法通过。任何帮助将不胜感激,因为这是此任务的最后一部分。非常感谢!

【问题讨论】:

    标签: regex pandas split


    【解决方案1】:

    另一种可能是:

    # Create the new two columns
    df[["Column B", "Column C"]]=df["Column A"].str.split('[', expand=True)
    # Get rid of the extra bracket
    df["Column C"] = df["Column C"].str.replace("]", "")
    # Get rid of the NaN and the useless column
    df = df.fillna(0).drop("Column A", axis=1)
    # Convert all columns to numeric
    df = df.apply(pd.to_numeric)
    

    【讨论】:

      【解决方案2】:

      你可以使用

      import pandas as pd
      df = pd.DataFrame({'Column A': ['1234[321]', '321[3]', '123', '456[456]']})
      df[['Column B', 'Column C']] = df['Column A'].str.extract(r'^(\d+)(?:\[(\d+)])?$', expand=False)
      # If you need to drop Column A here, use
      # df[['Column B', 'Column C']] = df.pop('Column A').str.extract(r'^(\d+)(?:\[(\d+)])?$', expand=False)
      df['Column C'][pd.isna(df['Column C'])] = 0
      df
      #    Column A Column B Column C
      # 0  1234[321]     1234      321
      # 1     321[3]      321        3
      # 2        123      123        0
      # 3   456[456]      456      456
      

      请参阅regex demo。它匹配

      • ^ - 字符串开头
      • (\d+) - 第 1 组:一位或多位数字
      • (?:\[(\d+)])? - 一个可选的非捕获组匹配[,然后捕获到第 2 组一个或多个数字,然后是 ]
      • $ - 字符串结束。

      【讨论】:

      • 正则表达式解决方案确实很强大,但初学者可能很难理解。 regex101 对理解语法非常有帮助。赞成这个答案。
      猜你喜欢
      • 2021-07-09
      • 2016-12-31
      • 2020-05-12
      • 2018-02-19
      • 2015-11-18
      • 2019-10-19
      • 1970-01-01
      • 2021-08-09
      相关资源
      最近更新 更多