[英]Replace start or end of string in values of pandas column with regex
With sed, I can do有了 sed,我可以做到
$ sed 's/^/prefix/' <<EOF
> foo
> EOF
prefixfoo
When I use pandas.Series.str.replace , the regex does not work.当我使用pandas.Series.str.replace时,正则表达式不起作用。 The minimal working example
最小的工作示例
import pandas as pd
df = pd.DataFrame({"text": ["foo", "bar"]})
df.text.str.replace("^", "prefix", regex=True)
returns回报
0 foo
1 bar
Name: text, dtype: object
It works if you capture the ^
:如果您捕获
^
它会起作用:
df['text'].str.replace(r'(^)', 'prefix', regex=True)
Output: Output:
0 prefixfoo
1 prefixbar
Name: text, dtype: object
That said the best method to prepend a string would be to concatenate:那就是说,添加字符串前缀的最佳方法是连接:
'prefix'+df['text']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.