正则表达式的列大熊猫
问题描述:
我的问题是如何利用re
替换字符串包含在数据帧:正则表达式的列大熊猫
当我使用re.sub()
,它给了我一个错误:
p = re.compile('New')
p.sub('old', df['Col1'])
而且,我尝试使用for循环,但放出来是意外,并在所有其他行显示的第一行的值:
for i in df['Col1']:
p.sub('old', i)
print(i)
我敢肯定,我失去了一些东西。
答
我认为你可以使用str.replace
,这与regex
也可以工作:
df = pd.DataFrame({'Col1':['sss old','dd','old']})
print (df)
Col1
0 sss old
1 dd
2 old
df.Col1 = df.Col1.str.replace('old','new')
print (df)
Col1
0 sss new
1 dd
2 new
谢谢@jezrael代码工作。 –
还有一个问题:当我想用str.startswith重新使用。它返回所有值false.i.e:df.col1.str.startswith('(N | n)ew'),我错过了什么? –
[str.startswith](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.startswith.html)不适用于正则表达式。 – jezrael