【问题标题】:regex: change "white space" chracter and - character to null正则表达式:将“空白”字符和 - 字符更改为 null
【发布时间】:2021-01-02 01:25:21
【问题描述】:
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))

我如何用正则表达式替换任何whitespace 字符和-
使用我的代码,返回:

          A        B    C
0 -0.532681  foo sai    0
1  1.490752      bar    1
2 -1.387326     foo-    -
3  0.814772      baz  NaN
4 -0.222552        -  NaN
5 -1.176781      qux  NaN

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

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    你可以使用

    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
    

    ^[\s-]+$ 模式匹配

    • ^ - 字符串开头
    • [\s-]+ - 一个或多个空格或- 字符
    • $ - 字符串结束。

    【讨论】:

    • 对于我的教育,这不是分别替换了foo bar 中的空间^ &amp; $ 吗?
    • @Manakin 是的,这些是字符串锚,见Anchors
    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2021-12-26
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多