Python regex:change";“空白”;字符和-字符为空
如何用正则表达式替换任何Python regex:change";“空白”;字符和-字符为空,python,regex,pandas,Python,Regex,Pandas,如何用正则表达式替换任何空格字符和-? 使用我的代码,返回以下内容: import pandas as pd import numpy as np df = pd.DataFrame([ [-0.532681, 'foo sai', 0], [1.490752, 'bar', 1], [-1.387326, 'foo-', '-'], [0.814772, 'baz', ' - '], [-0.222552, ' -', ' -'],
空格
字符和-
?
使用我的代码,返回以下内容:
import pandas as pd
import numpy as np
df = pd.DataFrame([
[-0.532681, 'foo sai', 0],
[1.490752, 'bar', 1],
[-1.387326, 'foo-', '-'],
[0.814772, 'baz', ' - '],
[-0.222552, ' -', ' -'],
[-1.176781, 'qux', '- '],
], columns='A B C'.split())
print(df)
print('-------------------------------')
print(df.replace(r'[^\w][\s]', np.nan, regex=True))
但我期望的返回是:
A、B、C
0-0.532681富赛0
1 1.490752巴1
2-1.387326富南
3 0.814772巴兹南
4-0.222552楠楠楠
5-1.176781库克斯南
您可以使用
but return that i expect is this:<br>
A B C
0 -0.532681 foo sai 0
1 1.490752 bar 1
2 -1.387326 foo- Nan
3 0.814772 baz NaN
4 -0.222552 Nan NaN
5 -1.176781 qux NaN
输出:
df.replace(r'^[\s-]+$', np.nan, regex=True)
^[\s-]+$
模式匹配
-字符串的开头^
-一个或多个空格或[\s-]+
字符-
-字符串结束$
^&$
的原因,这不会取代foo bar
中的空格吗?@Manakin是的,这些是字符串锚,请参阅。
df.replace(r'^[\s-]+$', np.nan, regex=True)
A B C
0 -0.532681 foo sai 0.0
1 1.490752 bar 1.0
2 -1.387326 foo- NaN
3 0.814772 baz NaN
4 -0.222552 NaN NaN
5 -1.176781 qux NaN