简体   繁体   English

将函数应用于数据帧的每一行

[英]apply a function to each row of the dataframe

What is a more elegant way of implementing below? 下面实施的更优雅的方式是什么?

I want to apply a function: my_function to a dataframe where each row of the dataframe contains the parameters of the function. 我想将一个函数: my_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])

We'll iterate through the values and build a DataFrame at the end. 我们将遍历这些值并在最后构建一个DataFrame。

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

The less recommended method is using DataFrame.apply : 不太推荐的方法是使用DataFrame.apply

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

The only advantage of apply is less typing. 唯一的好处apply是打字少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM