Python 去除熊猫数据帧列中的所有尾随空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34446767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stripping all trailing empty spaces in a column of a pandas dataframe
提问by headdetective
I have a pandas DFthat has many string elementsthat contains words like this:
我有一个Pandas DF,它有许多包含以下单词的字符串元素:
'Frost '
Which has many leading white spaces in front of it. When I compare this string to:
它前面有许多领先的空白。当我将此字符串与:
'Frost'
I realized that the comparison was Falsedue to the leading spaces.
我意识到由于领先的空格,比较是错误的。
Although I can solve this by iterating over every element of the pandas DF, the process is slow due to the large number of records I have.
虽然我可以通过迭代 pandas DF 的每个元素来解决这个问题,但由于我拥有大量记录,这个过程很慢。
This other approach should work, but it is not working:
这种另一种方法应该有效,但它不起作用:
rawlossDF['damage_description'] = rawlossDF['damage_description'].map(lambda x: x.strip(''))
So when I inspect an element:
所以当我检查一个元素时:
rawlossDF.iloc[0]['damage_description']
It returns:
它返回:
'Frost '
What's going on here?
这里发生了什么?
采纳答案by Luis Miguel
Replace your function with this:
用这个替换你的函数:
rawlossDF['damage_description'] = rawlossDF['damage_description'].map(lambda x: x.strip())
You almost had it right, you needed to get rid off the '' inside strip()
你几乎做对了,你需要摆脱 '' 里面的 strip()