Python 如何删除空白?
我有一个包含很多特殊字符和多个空格的数据框。特别是一列有很多空格 看起来是这样的: 所以我这样做了:Python 如何删除空白?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个包含很多特殊字符和多个空格的数据框。特别是一列有很多空格 看起来是这样的: 所以我这样做了: def remove_whitespace(strings): x = strings.replace(" ", "") return x df['Clean'] = df[0].apply(remove_whitespace) 但什么也没发生。我做错了什么?我认为您的代码有问题。您的函数正在获取一个参数,在您的情况下,您没有为它传递一个值 def remove_white
def remove_whitespace(strings):
x = strings.replace(" ", "")
return x
df['Clean'] = df[0].apply(remove_whitespace)
但什么也没发生。我做错了什么?我认为您的代码有问题。您的函数正在获取一个参数,在您的情况下,您没有为它传递一个值
def remove_whitespace(strings):
x = strings.replace(" ", "")
return x
df['Clean'] = df[0].apply(remove_whitespace(strings))
应用此解决方案:
string
将函数应用于数据帧中的每个元素-使用applymap
df.applymap(lambda x: x.strip() if type(x)==str else x)
你也可以试试这个
def remove(string):
return "".join(string.split())
string = ' s t r i n g'
print(remove(string))
输出:
string
使用
split()
函数返回字符串中的单词列表。然后使用join()
连接iterable。如果您正在使用pandas dataframe:那么您可能应该尝试,df['newcol']=df['column'].str.replace(r'\s+','',regex=True)
,对于vanila python,导入re
re.sub(r'\s+','',input_string)
@beapbeep像我在解决方案中那样使用applymap。