Abigail Min NM
Abigail Min NM

Reputation: 61

How to insert a column while iterating a dataframe?

for index, row in df.iterrows():
    row['new_column'] = caculate_value(row)

Like above, I want to insert a new column for each row. How to put this row with new column back to the df?

Upvotes: 0

Views: 144

Answers (2)

Jay Kakadiya
Jay Kakadiya

Reputation: 541

you need to use apply function outside of the loop like below

for index, row in df.iterrows():
    row['new_column'] = caculate_value(row)

df['new_column'] = df.apply(calculate_value, axis=1)

Upvotes: 0

Eric Truett
Eric Truett

Reputation: 3010

Use apply

df['new_column'] = df.apply(calculate_value, axis=1)

Upvotes: 1

Related Questions