Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何删除空白?_Python_Python 3.x_Pandas - Fatal编程技术网

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。