gpt4 book ai didi

python - 正则表达式:将 "white space"字符和 - 字符更改为空

转载 作者:行者123 更新时间:2023-12-03 16:48:01 25 4
gpt4 key购买 nike

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

最佳答案

您可以使用

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-]+ - 一个或多个空格或 -字符
  • $ - 字符串的结尾。
  • 关于python - 正则表达式:将 "white space"字符和 - 字符更改为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63899277/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com