0

I am newby to Pandas and maybe my question/problem is very easy. I have a dataframe with shape n*3 and I want to create a new column (fourth) where I will add the values of the other columns (column1 + column2 + column3)

I tried this and although I print the sum with correct summary values I cannot save it to the new column.

for index, row  in answers.iterrows():
    mydf[index, 3] = mydf.iloc[index, 0] + mydf.iloc[index, 1] + mydf.iloc[index, 2]
Er1Hall
  • 147
  • 2
  • 11

1 Answers1

1

Use DataFrame.sum():

mydf['sum'] = mydf.sum(axis=1)

If you want only few columns, make a column list and the sum over them:

col_list =['col1', 'col2', 'col3']
mydf['sum'] = mydf[col_list].sum(axis=1)
Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45