2

I want to sum multiple columns of dataframe to a new column. For 2 columns I was using this.

    import pandas as pd, numpy as np
    df=pd.read_csv("Calculation_test.csv")

    #creating new colums
    df["Test1"] = 0

    #sum of 2 columns

    df["Test1"]= df['col1']+df['col2']
    df.to_csv('test_cal.csv', index=False)

But, for my project, I need to do sums of around 15-20 columns. Every time I do not want to write df['col1']+df['col2']+......................

I have the list of columns, which I have to add. Like:

'col1'+'col2'+ 'col5'+'col8'+----+'col18'

or like this:

'col1', 'col2', 'col5', 'col8',----,'col18'

How can I use this list directly to do the sum of columns?

Tashaho
  • 163
  • 1
  • 2
  • 11

1 Answers1

2

Try slicing the columns:

import pandas as pd
df = pd.read_csv("whatever.csv")
df.loc[:,'col1':'col18'].sum(axis = 1)