我有一个包含很多特殊字符和多个空格的数据框。特别是一列有很多空白。
看起来像这样:
所以我这样做了:
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))
应用此解决方案:
将函数应用于数据框中的每个元素-使用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()
串联可迭代对象。