python - 如何拆分/提取新列并从列中删除提取的字符串

标签 python pandas dataframe split extract

我有一个示例数据框

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.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

关于python - 如何拆分/提取新列并从列中删除提取的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67400124/

相关文章:

python - Pyserial 在 Windows 上的非阻塞/忙等待用法 : How to monitor multiple serial ports in real time?

python - 在 pandas df 列上嵌套 "ifs"

python - 按列表中的值过滤 pandas DataFrame

python - 使用已在 python 中设置的一些变量生成真值表

Python如何找出一个文本文件中的唯一元素并输出到另一个文本文件中

python - 在 NaN 行拆分数据框

r - 如何使用 r 传播数据

python - 来自 Pandas 数据框的共现矩阵

Python研究

python - 按数据框中每组 bool 值出现的次数进行过滤