我如何删除空格?

问题描述 投票:1回答:1

我有一个包含很多特殊字符和多个空格的数据框。特别是一列有很多空白。

看起来像这样:

enter image description here

所以我这样做了:

def remove_whitespace(strings):
    x = strings.replace(" ", "")
    return x

df['Clean'] = df[0].apply(remove_whitespace)

但没有任何反应。我在做什么错?

python python-3.x pandas
1个回答
2
投票

我认为您的代码有问题。您的函数正在获取参数,而您没有为它传递值。

def remove_whitespace(strings):
    x = strings.replace(" ", "")
    return x

df['Clean'] = df[0].apply(remove_whitespace(strings))

应用此解决方案:

将函数应用于数据框中的每个元素-使用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()串联可迭代对象。

© www.soinside.com 2019 - 2024. All rights reserved.