【问题标题】:Can not remove white spaces from DataFrame [duplicate]无法从 DataFrame 中删除空格 [重复]
【发布时间】:2021-05-09 13:53:39
【问题描述】:

我无法从 DataFrame 中删除空格。尝试下一条路径但没有成功:.replace(' ', '')

csv 文件 - https://drive.google.com/file/d/1AjlFYxGPUqVFkxW6QXA6hNRjkLR8eTFP/view?usp=sharing

请帮我解决这个问题。有问题的列是“gdp_per_capita”

【问题讨论】:

  • df['gdp_per_capita'].str.replace('\s+', '', regex=True).astype(int)
  • @Ferris Perfect。谢谢

标签: pandas


【解决方案1】:

要从串行字符串或数据框对象中替换空格,请使用str.replace() 方法。

例如:

>>> import pandas as pd
>>> ser = pd.Series(['aaa ','aac vf','cc  '])
>>> ser
0      aaa 
1    aac vf
2      cc  
dtype: object

>>> ser[0]
'aaa '

>>> len(ser[0])
4

>>> ser.str.replace(" ", "")
0      aaa
1    aacvf
2       cc
dtype: object

如您所见,replace 方法删除了字符串中的空格。

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多