将函数应用于 DataFrame 中的每个单元格 [英] Apply function to each cell in DataFrame

查看:30
本文介绍了将函数应用于 DataFrame 中的每个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可能如下所示的数据框:

I have a dataframe that may look like this:

A        B        C
foo      bar      foo bar
bar foo  foo      bar

我想查看每行的每个元素(或每列的每个元素)并应用以下函数来获取后续的 DF:

I want to look through every element of each row (or every element of each column) and apply the following function to get the subsequent DF:

def foo_bar(x):
    return x.replace('foo', 'wow')

A        B        C
wow      bar      wow bar
bar wow  wow      bar

是否有一个简单的单行程序可以将一个函数应用到每个单元格?

Is there a simple one-liner that can apply a function to each cell?

这是一个简单的示例,因此除了应用函数之外,可能还有一种更简单的方法来执行此特定示例,但我真正要问的是如何在数据帧内的每个单元格中应用函数.

This is a simplistic example so there may be an easier way to execute this specific example other than applying a function, but what I am really asking about is how to apply a function in every cell within a dataframe.

推荐答案

您可以使用 applymap() 这对你的情况很简洁.

You can use applymap() which is concise for your case.

df.applymap(foo_bar)

#     A       B       C
#0  wow     bar wow bar
#1  bar wow wow     bar

另一种选择是矢量化您的函数,然后使用 apply 方法:

Another option is to vectorize your function and then use apply method:

import numpy as np
df.apply(np.vectorize(foo_bar))
#     A       B       C
#0  wow     bar wow bar
#1  bar wow wow     bar

这篇关于将函数应用于 DataFrame 中的每个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆