Python 从 DataFrame 字符串字段中去除所有空格

标签 python string replace strip spaces

我有一个带有以下列的数据框:

enter image description here

我正在尝试删除所有空格(前导、尾随和中间的)。例如,“低电位”应显示为“低电位”。我已经尝试过以下代码,但它似乎不起作用:

df_merged_1['Priority Type'] = df_merged_1['Priority Type'].replace(' ', '')

非常感谢任何帮助!

最佳答案

您可以使用str.replace方法; Series.replace 方法旨在按字面替换值(完全匹配),即替换系列中的空白值,而不是从字符串中删除空白:

df_merged_1['Priority Type'] = df_merged_1['Priority Type'].str.replace(' ', '')

或者,您可以在替换方法中指定regex=True:

df_merged_1['Priority Type'] = df_merged_1['Priority Type'].replace(' ', '', regex=True)

关于Python 从 DataFrame 字符串字段中去除所有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43573718/

相关文章:

python - Google Drive API V3 从快捷方式获取原始文件

python - NLP预处理词时如何保留特定词?(str.replace & regex)

ios - Xamarin.ios:在 .Split (","之后列出跳过代码的字符串)

java - Java中分割字符串

Python 属性错误 : NoneType object has no attribute 'close'

python - 如何使用 python 在文件中查找一组最常出现的词对?

c - 哪个效率更高 : char str[] or char *str?

regex - 使用 awk 打印正则表达式组的长度

regex - Intellij 想法 : how to put dollar sign to the replaced content

c++ - 要求编辑文本,文本格式