Miguel
Miguel

Reputation: 3064

python add elements to dataframe row

I'm iterating over a dataframe and I want to add new elements to each row, so that I can add the new row to a second dataframe.

for index, row in df1.iterrows():
    # I looking for somethis like this:
    new_row = row.append({'column_name_A':10})

    df2 = df2.append(new_row,ignore_index=True)

Upvotes: 0

Views: 109

Answers (1)

Abhinav Upadhyay
Abhinav Upadhyay

Reputation: 2585

If I understand correctly, you want to have a copy of your original dataframe with a new column added. You can create a copy of the original dataframe, add the new column to it and then iterate over the rows of the new dataframe to update the values of the new column as you would have done in your code posted in the question.

df2 = df1.copy()
df2['column_name_A'] = 0
for index, row in df2.iterrows():
    row['column_name_A'] = some_value

Upvotes: 1

Related Questions