Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python regex:change";“空白”;字符和-字符为空_Python_Regex_Pandas - Fatal编程技术网

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