RJL*_*RJL 6 python dataframe pandas
我是python的新手,所以这可能是一个非常基本的问题.我正在尝试使用lambda来删除pandas数据帧中每一行的标点符号.我使用了以下内容,但收到了错误.我试图避免将df转换为列表然后将清理后的结果附加到新列表中,然后将其转换回df.
任何建议,将不胜感激!
import string
df['cleaned'] = df['old'].apply(lambda x: x.replace(c,'') for c in string.punctuation)
Run Code Online (Sandbox Code Playgroud)
ber*_*nie 11
您需要迭代数据框中的字符串,而不是遍历string.punctuation.您还需要使用备份来构建字符串.join().
df['cleaned'] = df['old'].apply(lambda x:''.join([i for i in x
if i not in string.punctuation]))
Run Code Online (Sandbox Code Playgroud)
当lambda表达式变得很长时,单独写出函数定义会更具可读性,例如(感谢@AndyHayden的优化提示):
def remove_punctuation(s):
s = ''.join([i for i in s if i not in frozenset(string.punctuation)])
return s
df['cleaned'] = df['old'].apply(remove_punctuation)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7066 次 |
| 最近记录: |