import pandas as pd
df=pd.DataFrame({'A':['my text your text']})
我想提取 A
列中的部分字符串,即 my text
到 B
列,并将其从 A
提取后。
在这种情况下,我要做的第一件事是适本地创建 B 列,然后从 A 中减去 B,但是有没有更好的解决方案来做到这一点?
df['B']=df['A'].str.extract('(my text)')
df
A B
0 my text your text my text
预期输出:
A B
0 your text my text
最佳答案
使用Series.str.replace
使用 \s*
删除尾随空格,使用 n=1
仅替换第一个匹配项:
df['B']=df['A'].str.extract('(my text)')
df['A']=df['A'].str.replace('\s*(my text)\s*','', n=1)
print (df)
A B
0 your text my text
关于python - 提取字符串并将其从提取的列 pandas 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61320227/