【问题标题】:How to split/extract a new column and remove the extracted string from the column如何拆分/提取新列并从列中删除提取的字符串
【发布时间】:2021-05-05 11:09:31
【问题描述】:

我有一个示例数据框

data = {"col1" : ["1 first 1", "2 second 2", "third 3", "4 fourth 4"]}

df = pd.DataFrame(data)
print(df)


     col1
0   1 first 1
1   2 second 2
2     third 3
3   4 fourth 4

我想提取列中的第一个digit 并删除它们

我试图提取使用

df["index"] = df["col1"].str.extract('(\d)')
    col1       index
0   1 first 1   1
1   2 second 2  2
2   third 3     3
3   4 fourth 4  4

如果我使用replace,我想从col1 中删除提取的数字,开始和结束数字都将被替换。

期望的输出

    col1    index
0   first 1     1
1   second 2    2
2   third 3     NaN
3   fourth 4    4

【问题讨论】:

    标签: python pandas dataframe split extract


    【解决方案1】:

    使用Series.str.replaceSeries.str.extractDataFrame.assign 分别处理每一列:

    #added ^ for start of string
    pat = '(^\d)'
    df = df.assign(col1 = df["col1"].str.replace(pat, '', regex=True),
                   index= df["col1"].str.extract(pat))
    print (df)
            col1 index
    0    first 1     1
    1   second 2     2
    2    third 3   NaN
    3   fourth 4     4
    

    【讨论】:

      【解决方案2】:

      使用regex 模式'^(\d)',这意味着您要访问字符串开头的一位数字。

      • ^ 指的是字符串的开头。
      • \d 表示一位数
      df["index"] = df.col1.str.extract("^(\d)")
      df.col1 = df.col1.str.replace('^(\d)',"",regex = True)
      
      print(df)
      
            col1   index
      0    first 1     1
      1   second 2     2
      2    third 3   NaN
      3   fourth 4     4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-23
        • 2021-11-07
        • 1970-01-01
        相关资源
        最近更新 更多