Compare column value to an int in dataframe with python

2921 views python

I have a dataframe dframe and i want to iterate over lines of my column number if number <5 then my column STATE takes the value 'vv' if number is between [5..17] so my value of my column STATE takes 'xx'. ELSE STATE takes 'yy'. SO I wrote this code but it doesn't work..

ANy helps please.

thank you `

for it in dframe['number']:
        if (it < 5):
            dframe['STATE'] = 'vv'
        elif (it >= 5 & it < 17):
            dframe['STATE'] = 'xx' 
            dframe['STATE'] = 'yy'`

answered question

3 Answers


Below code should work for you.


for i in range(0,len(dframe)):
   `    it = dframe.iloc[i]['number']
        if (it < 5):
            dframe.iloc[i]['STATE'] = 'vv'
        elif (it >= 5 & it < 17):
            dframe.iloc[i]['STATE'] = 'xx' 
            dframe.iloc[i]['STATE'] = 'yy'`

posted this

You can do this in one line with a list comprehension:

dframe['state'] = ['vv' if (i < 5) else 'xx' if (i >= 5) & (i < 17) else 'yy' for i in dframe['number']]

posted this

npm cache clean --force fixed the issue.

posted this

Have an answer?


Please login first before posting an answer.