【问题标题】:Stripping all trailing empty spaces in a column of a pandas dataframe剥离熊猫数据框列中的所有尾随空格
【发布时间】:2015-12-24 14:54:39
【问题描述】:

我有一个 pandas DF,其中包含许多 字符串元素,其中包含以下单词:

'Frost                              '

它前面有许多前导空格。当我将此字符串与以下内容进行比较时:

'Frost'

由于前导空格,我意识到比较是错误

虽然我可以通过遍历 pandas DF 的每个元素来解决这个问题,但由于我拥有大量记录,这个过程很慢。

这种其他方法应该有效,但它不起作用:

rawlossDF['damage_description'] = rawlossDF['damage_description'].map(lambda x: x.strip(''))

所以当我检查一个元素时:

rawlossDF.iloc[0]['damage_description']

返回:

'Frost                              '

这是怎么回事?

【问题讨论】:

    标签: python pandas strip


    【解决方案1】:

    您也可以使用str.strip 方法:

    rawlossDF['damage_description'] = rawlossDF['damage_description'].str.strip()
    

    【讨论】:

    • 我在一个 5M 行的数据集上尝试了这个,与 map+lambda 相比,它需要两倍的时间
    【解决方案2】:

    用这个替换你的函数:

    rawlossDF['damage_description'] = rawlossDF['damage_description'].map(lambda x: x.strip())
    

    你几乎做对了,你需要去掉strip()里面的''

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-07
      • 2023-01-09
      • 2018-10-14
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      相关资源
      最近更新 更多