我有一个示例数据框
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
我想提取列中的第一个数字
并将其删除
我尝试使用提取
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
最佳答案
使用Series.str.replace
与 Series.str.extract
与 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
关于python - 如何拆分/提取新列并从列中删除提取的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67400124/