对数据帧的每一行应用一个函数 [英] apply a function to each row of the dataframe

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

问题描述

下面有什么更优雅的实现方式?

What is a more elegant way of implementing below?

我想应用一个函数:my_function 到一个数据帧,其中数据帧的每一行都包含函数的参数.然后我想将函数的输出写回数据帧行.

I want to apply a function: my_function to a dataframe where each row of the dataframe contains the parameters of the function. Then I want to write the output of the function back to the dataframe row.

results = pd.DataFrame()
for row in input_panel.iterrows():
    (index, row_contents) = row
    row_contents['target']  = my_function(*list(row_contents))
    results = pd.concat([results, row_contents])

推荐答案

我们将遍历这些值并在最后构建一个 DataFrame.

We'll iterate through the values and build a DataFrame at the end.

results = pd.DataFrame([my_function(*x) for x in input_panel.values.tolist()])

不太推荐的方法是使用DataFrame.apply:

The less recommended method is using DataFrame.apply:

results = input_panel.apply(lambda x: my_function(*x))

apply 的唯一优点是少打字.

The only advantage of apply is less typing.

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

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