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

Viewed 39

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
2 Answers
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

For one liner conditions in Python, elif doesn't work.

There are 2 ways that you can create the new column

  1. With a one-liner if-else ladder. (This is okay when you have only a certain number of conditions)
    df["solar_panel_area"] = [
        4 if x < 100
        else 6 if x < 200
        else 8 if x < 300
        else 12
        for x in df["floor_area"]
    ]
    
  2. Create a function and use df['column'].map(f)
    def solar_panel_area(floor_area):
        if floor_area < 100:
            return 4
        elif floor_area < 200:
            return 6
        elif floor_area<300:
            return 8
        else:
            return 12
    df["solar_panel_area"] = df["floor_area"].map(solar_panel_area)
    
    This works because you want to work on only a single column of data. A single column of a DataFrame is a pandas.Series. map is fast as it can work in parallel. If you need to incorporate multiple columns, you need to use df.apply

Related