Search code examples
dataframesumlist-comprehensionmultiple-columnspython-3.7

How to sum up columns in pandas DataFrame


I have the following dataset:

data = [{'Title': 'Size', 'B': 20, 'C':30, 'D':15, 'E':15},
    {'Title': 'Length', 'B': 50,'C':60, 'D':14,'E':15}, 
    {'Title': 'Area', 'B': 4,'C':3, 'D':13,'E':15}]

df = pd.DataFrame(data)

enter image description here

And I would like sum up columns 'C' and 'E' and name the column containing the summed up value as "Total".

The end result should look like this:

enter image description here

I read that avoiding looping is a good idea and 'list comprehension' should be used, so I tried the code below but it doesn't work:

df2 = []
result = [(row[0]) for row in df[iloc.:,[2,4]].sum(axis=1).to_numpy()]
df2.append(result)

Solution

  • df['Total'] = df['C'] + df['E']
    df = df[['Title','Total']]