Compare column value to an int in dataframe with python

2921 views python
-1

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' 
        else: 
            dframe['STATE'] = 'yy'`

answered question

3 Answers

13

Below code should work for you.

dframe['state']=''

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' 
        else: 
            dframe.iloc[i]['STATE'] = 'yy'`

posted this
13

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
4

npm cache clean --force fixed the issue.

posted this

Have an answer?

JD

Please login first before posting an answer.