Lisa
Lisa

Reputation: 4416

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

Upvotes: 8

Views: 5921

Answers (1)

cs95
cs95

Reputation: 402263

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.

Upvotes: 9

Related Questions