如何 split/extract 一个新列并从该列中删除提取的字符串

How to split/extract a new column and remove the extracted string from the column

我有一个示例数据框

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

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

期望输出

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

使用Series.str.replace with Series.str.extract with DataFrame.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

使用 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