python - 将函数应用于数据框中的列 - python

标签 python

我编写了一个函数来消除数据框中值的空格。

def eliminate_space(words):
    return words.replace(' ', '')

现在我想将该函数应用于数据帧“单词”列中的每一行。

df['words']=df['words'].apply(eliminate_space(words))

它表示名称“words”未定义。如何调整我的代码以便能够将该函数应用于数据帧该列中的每个值?

最佳答案

您可以将 applylambda 一起用于 row 的该列:

df['words']=df['words'].apply(lambda row: eliminate_space(row))

使用示例进行测试:

df = pd.DataFrame({'words':['word is 1', 'word is 2', 'word is 3']})
print(df)

初始数据框:

     words
0  word is 1
1  word is 2
2  word is 3

使用函数:

df['words']=df['words'].apply(lambda row: eliminate_space(row))

结果:

     words
0  wordis1
1  wordis2
2  wordis3

关于python - 将函数应用于数据框中的列 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47725715/

相关文章:

python - 如何从图像中剪切轮廓并将其保存到新文件

Python 数学模块显示完全错误的结果?

python - 运行时的 Airflow 动态任务

python - 读取 .sql 文件以在 Python 中执行 (pymysql)

python - AWS CDK 管道 : How to access internal stack values in post-stage steps?

python - 使用 Splinter 操纵浏览器(窗口)大小

python - 没有创建 pid 并且进程没有启动的任何原因?

python - 在 python 中检查重复项的最快方法是什么?

python - 从 8 位数组转换为 5 位数组

python - 入队调用中的 rq 超时参数不起作用,给出 JobTimeoutException