pandas 删除 DataFrame 中的多个空白
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43071415/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:17:40 来源:igfitidea点击:
Remove Multiple Blanks In DataFrame
提问by Bertug
How do I remove multiple spaces between two strings in python.
如何在python中删除两个字符串之间的多个空格。
e.g:-
例如:-
"Bertug 'here multiple blanks' Mete" => "Bertug Mete"
to
到
"Bertug Mete"
Input is read from an .xls file. I have tried using split() but it doesn't seem to work as expected.
输入是从 .xls 文件中读取的。我试过使用 split() 但它似乎没有按预期工作。
import pandas as pd , string , re
dataFrame = pd.read_excel("C:\Users\Bertug\Desktop\example.xlsx")
#names1 = ''.join(dataFrame.Name.to_string().split())
print(type(dataFrame.Name))
#print(dataFrame.Name.str.split())
Let me know where I'm doing wrong.
让我知道我哪里做错了。
回答by jezrael
I think use replace
:
我认为使用replace
:
df.Name = df.Name.replace('\s+', ' ', regex=True)
Sample:
样本:
df = pd.DataFrame({'Name':['Bertug Mete','a','Joe Black']})
print (df)
Name
0 Bertug Mete
1 a
2 Joe Black
df.Name = df.Name.replace('\s+', ' ', regex=True)
#similar solution
#df.Name = df.Name.str.replace('\s+', ' ')
print (df)
Name
0 Bertug Mete
1 a
2 Joe Black