0

i want to map the the AQI column with AQI_Bucket column in pandas dataframe i tried it using for loop but couldnt get it

for aqi in df['AQI']:
    col1,col2 = df['AQI'],df['AQI_Bucket']
    _col1,_col2 = col1[0],col2[0]
    if df[aqi] == df['AQI_Bucket']:
        
        if pd.isnull(_col2):
            if _col1 in range(51):
                _col2 = "Good"
            elif _col1 in range(51, 101):
                _col2 = "Satisfactory"
            elif _col1 in range(101,201):
                _col2 = "Moderate"
            elif _col1 in range(201, 301):
                _col2 = "Poor"
            elif _col1 in range(301, 401):
                _col2 == "Very Poor"
            elif _col1 in range(401, 500):
                _col2 == "Severe"

  • Hello, please read about [how to make good, reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – Steele Farnsworth May 28 '22 at 22:21
  • From what I infer from your code, you want to fill null values of `AQI_Bucket` column based on the value of `AQI` (`range(51) => "Good"`, etc). Is it correct? – NoThlnG May 28 '22 at 22:48

1 Answers1

0

I'm pretty sure I know what you're trying to do here, and you should definitely use the .cut() method:

import numpy as np
import pandas as pd

#generate a DF with 2 columns, 1 with random values, the other with fixed values
df = pd.DataFrame({'AQI_rand': np.random.randint(500, size=6),\
                   'AQI_fixed': [25,75,150,250,350,450]}) #I've made this one to check if the "bins" were correct

#create the first "AQI_Bucket" column linked to "AQI_rand"
df['AQI_Bucket'] = pd.cut(df['AQI_rand'], bins=[0,50,100,200,300,400,500], labels=['Good','Satisfactory','Moderate','Poor','Very Poor','Severe'])

#create the first "AQI_Bucket2" column linked to "AQI_fixed"
df['AQI_Bucket2'] = pd.cut(df['AQI_fixed'], bins=[0,50,100,200,300,400,500], labels=['Good','Satisfactory','Moderate','Poor','Very Poor','Severe'])

#rearrange columns order
df = df.iloc[:,[0,2,1,3]]
df
index AQI_rand AQI_Bucket AQI_fixed AQI_Bucket2
0 326 Very Poor 25 Good
1 238 Poor 75 Satisfactory
2 182 Moderate 150 Moderate
3 341 Very Poor 250 Poor
4 88 Satisfactory 350 Very Poor
5 459 Severe 450 Severe

If it's not what you were looking for, please let me know and I'll delete my answer, otherwise check mark it

Drakax
  • 1,305
  • 3
  • 9