apply a function to each row of the dataframe

余生颓废 提交于 2020-01-24 03:04:27

问题


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. 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])

回答1:


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()])

The less recommended method is using DataFrame.apply:

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

The only advantage of apply is less typing.



来源:https://stackoverflow.com/questions/50421196/apply-a-function-to-each-row-of-the-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!