create a column on a dataframe using several if conditions intervals on python

I have a df and I would like to add a column ‘solar_panel_area’ depending on several conditions of other df column named ‘floor area’. the conditions are:

  • floor area < 100 return 4
  • 100 <floor area<200 return 6
  • 200 <floor area<300 return 8
  • else return 12
import pandas as pd data = {'id': ['B100'], 'floor_area': [20]}
df =pd.DataFrame(data)

I tried:

df[‘solar_panel_area’]= [4 if x<100 elif 6 x<200 & 8 x<300 else 12 for x in > (pair[‘floor_area’])]

get synthax error on elif

If I just try with 2 conditions it is correct:

df['solar_panel_area']= [4 if x<100 else 12 for x in(df['floor_area'])]
df
id  floor_area  solar_panel_area
0   B100    20  4

Answer

def fn(x):
    if x < 100:
        return 4
    if 100 < x < 200:
        return 6
    if 200 < x < 300:
        return 8
    return 12


df["solar_panel_area"] = df["floor_area"].apply(fn)

print(df)

Prints:

     id  floor_area  solar_panel_area
0  B100          20                 4