Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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])
like image 507
Lisa Avatar asked May 19 '18 02:05

Lisa


1 Answers

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.

like image 186
cs95 Avatar answered Oct 06 '22 07:10

cs95