将函数应用于数据框的每一行 [英] apply a function to each row of the dataframe
本文介绍了将函数应用于数据框的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面实现哪种更优雅的方式?
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屋!
查看全文