Python 将函数应用于 DataFrame 中的每个单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39475978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:18:59  来源:igfitidea点击:

Apply function to each cell in DataFrame

pythonpandasdataframeapply

提问by eljusticiero67

I have a dataframe that may look like this:

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

A        B        C
foo      bar      foo bar
bar foo  foo      bar

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:

我想查看每行的每个元素(或每列的每个元素)并应用以下函数来获取后续的 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.

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

回答by Psidom

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

您可以使用applymap()which 对您的情况简洁。

df.applymap(foo_bar)

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

Another option is to vectorize your function and then use applymethod:

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

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