如何替换熊猫列中除字母和数字之外的所有内容?

时间:2018-07-26 17:10:56

标签: python python-3.x pandas

我有这样的df:

id    answer
1      how are you? 
2      What's the word in the letters'
3      .... \xa0 \xa0' Hey what's up?

如何在df.answer中将所有不是字母或数字的东西替换为空?

新df如下所示:

id    question
1      how are you 
2      Whats the word in the letters
3      Hey whats up 

2 个答案:

答案 0 :(得分:2)

df.answer = df.apply(lambda row: ''.join(i for i in row.answer if i.isalnum() or i==' '), axis=1)

这应该有效。

答案 1 :(得分:0)

您还可以使用re模块:

df['answer'] = df['words'].apply(lambda x: re.sub(r'\W+&\s','',x))

另一种选择:

df['words'].str.replace(r'\W+&\s', '')