【问题标题】:Removing characters from a string in pandas从熊猫中的字符串中删除字符
【发布时间】:2016-10-21 12:42:31
【问题描述】:

我有一个类似的问题:Pandas DataFrame: remove unwanted parts from strings in a column

所以我用了:

temp_dataframe['PPI'] = temp_dataframe['PPI'].map(lambda x: x.lstrip('PPI/'))

大多数项目以“PPI/”开头,但不是全部。似乎当一个没有'PPI/'后缀的项目遇到了这个错误:

AttributeError: 'float' 对象没有属性 'lstrip'

我错过了什么吗?

【问题讨论】:

  • 是缺失值还是实际浮动造成的?你能显示导致这种情况的行的值吗? (在这里尝试学习和理解)

标签: python pandas


【解决方案1】:

使用矢量化str.lstrip:

temp_dataframe['PPI'] = temp_dataframe['PPI'].str.lstrip('PPI/')

看起来您可能缺少值,因此您应该将它们屏蔽掉或替换它们:

temp_dataframe['PPI'].fillna('', inplace=True)

temp_dataframe.loc[temp_dataframe['PPI'].notnull(), 'PPI'] = temp_dataframe['PPI'].str.lstrip('PPI/')

也许更好的方法是使用str.startswith 过滤并使用split 并访问要删除的前缀之后的字符串:

temp_dataframe.loc[temp_dataframe['PPI'].str.startswith('PPI/'), 'PPI'] = temp_dataframe['PPI'].str.split('PPI/').str[1]

正如@JonClements 指出的那样,lstrip 正在删除空格,而不是删除您所追求的前缀。

更新

另一种方法是传递一个正则表达式模式,该模式查找可选前缀并提取前缀后的所有字符:

temp_dataframe['PPI'].str.extract('(?:PPI/)?(.*)', expand=False)

【讨论】:

  • 不要忘记 .lstrip 可能不是 OP 想要的 - 它会从字符串的开头删除所有 PI/ 字符- 如果存在前缀,它实际上并没有删除它......
  • 或者可能是temp_dataframe['PPI'].str.extract('(?:PPI/)?(.*)', expand=False)
【解决方案2】:

使用replace

temp_dataframe['PPI'].replace('PPI/','',regex=True,inplace=True)

string.replace:

temp_dataframe['PPI'].str.replace('PPI/','')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 2017-10-01
    • 2019-03-06
    • 2021-03-16
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多