jeudi 29 juillet 2021

How to check if number lies within many ranges?

I have a list of numbers from 1 to 24

hour = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

I want to create four separate lists (a, b, c, d) based on respective conditions:

a = (22<= number <6)
b = (6<= number <9 or 12<= number <18)
c = (9<= number <12)
d = (18<= number <22

if condition is True then 1 else 0

Expected output:

enter image description here


I can create the a column but with rest of them I am facing issue,

My attempt:

import pandas as pd
df = pd.read_excel('mask.xlsx')
hour = df['Hours']
df['a'] = [1 if i>=22 or i<6 else 0 for i in hour]
b=[]
for i,j in zip(hour, df['a']):
    if i <= 6 and i < 9:
        if i<=12 and i<18:
            if j==0:
                b.append(1)
    else:
        b.append(0)
df['b'] = b

Error I'm getting:

ValueError: Length of values does not match length of index

Aucun commentaire:

Enregistrer un commentaire