去除 pandas 数据框的一列中的所有尾随空格

Stripping all trailing empty spaces in a column of a pandas dataframe

我有一个 pandas DF,它有许多 字符串元素,其中包含这样的词:

'Frost                              '

它前面有很多前导空格。当我将此字符串与:

进行比较时
'Frost'

我意识到由于前导空格,比较结果是 False

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

另一种方法应该有效,但无效:

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

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

rawlossDF.iloc[0]['damage_description']

它returns:

'Frost                              '

这是怎么回事?

用这个替换你的函数:

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

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

或者您可以使用 str.strip 方法:

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