Sum-As-New-Column
Sat 17 May 2025
title: "Sum as a new column" author: "Rj" date: 2019-04-22 description: "-" type: technical_note draft: false
import numpy as np
import pandas as pd
df = pd.read_csv('abc.csv')
df
| student | language | science | maths | history | |
|---|---|---|---|---|---|
| 0 | kumar | 90 | 56 | 34 | 34 |
| 1 | kevin | 10 | 34 | 32 | 67 |
| 2 | sammy | 90 | 23 | 12 | 32 |
| 3 | janice | 20 | 67 | 90 | 45 |
| 4 | peter | 30 | 56 | 45 | 65 |
| 5 | prem | 90 | 45 | 45 | 34 |
| 6 | carrol | 50 | 90 | 45 | 23 |
df['total'] = df.sum()
df
| student | language | science | maths | history | total | |
|---|---|---|---|---|---|---|
| 0 | kumar | 90 | 56 | 34 | 34 | NaN |
| 1 | kevin | 10 | 34 | 32 | 67 | NaN |
| 2 | sammy | 90 | 23 | 12 | 32 | NaN |
| 3 | janice | 20 | 67 | 90 | 45 | NaN |
| 4 | peter | 30 | 56 | 45 | 65 | NaN |
| 5 | prem | 90 | 45 | 45 | 34 | NaN |
| 6 | carrol | 50 | 90 | 45 | 23 | NaN |
Note
The total coulmn shows NaN. This is because of missing axis.
df['total'] = df.sum(axis=1)
df
| student | language | science | maths | history | total | |
|---|---|---|---|---|---|---|
| 0 | kumar | 90 | 56 | 34 | 34 | 428 |
| 1 | kevin | 10 | 34 | 32 | 67 | 286 |
| 2 | sammy | 90 | 23 | 12 | 32 | 314 |
| 3 | janice | 20 | 67 | 90 | 45 | 444 |
| 4 | peter | 30 | 56 | 45 | 65 | 392 |
| 5 | prem | 90 | 45 | 45 | 34 | 428 |
| 6 | carrol | 50 | 90 | 45 | 23 | 416 |
Score: 5
Category: data-wrangling