Custom-Function-As-Lambda
Sat 17 May 2025
title: "Custom Function as Lambda" author: "Rj" date: 2019-04-22 description: "-" type: technical_note draft: false
import numpy as np
import pandas as pd
def apply_math_special(row):
return (row.maths *2 + (row.language/2) + (row.history/3) + (row.science/4))
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['math_special'] = df.apply(apply_math_special, axis=1).astype(int)
df
| student | language | science | maths | history | math_special | |
|---|---|---|---|---|---|---|
| 0 | kumar | 90 | 56 | 34 | 34 | 138 |
| 1 | kevin | 10 | 34 | 32 | 67 | 99 |
| 2 | sammy | 90 | 23 | 12 | 32 | 85 |
| 3 | janice | 20 | 67 | 90 | 45 | 221 |
| 4 | peter | 30 | 56 | 45 | 65 | 140 |
| 5 | prem | 90 | 45 | 45 | 34 | 157 |
| 6 | carrol | 50 | 90 | 45 | 23 | 145 |
What did we do?
We just doubled the math marks and reduced the marks of other subjects by 2, 3, 4 and then assigned the new value as a new column
Score: 5
Category: data-wrangling