Loc With Boolean

Sat 17 May 2025

title: "If Else Pandas" author: "Rj" date: 2019-04-24 description: "-" type: technical_note draft: false source: http://pandas.pydata.org/pandas-docs/version/0.24/user_guide/cookbook.html#idioms


import numpy as np
import pandas as pd
df = pd.DataFrame({
    'maths' : [80, 89, 90, 20],
    'science' : [40, 50, 90, 100],
    'language' : [20, 30, 90, 95]
})
df
maths science language
0 80 40 20
1 89 50 30
2 90 90 90
3 20 100 95
df.loc[df.maths > 50, 'maths_1'] = 90
df
maths science language maths_1
0 80 40 20 90.0
1 89 50 30 90.0
2 90 90 90 90.0
3 20 100 95 NaN


Score: 5

Category: data-wrangling