I'm trying to change a cell value (colour 'red' or 'green') based on a value of another cell. I run the following:
df.loc[0, 'Colour'] = df.loc[0, 'Count'].apply(lambda x: 'Red' if x <= 500
else 'Green')
I get the following error:
AttributeError: 'numpy.float64' object has no attribute 'apply'
any help is greatly appreciated
When you use df.loc[0, 'Count'] you are only returning the item that is actually that location which is a float. apply is a method of a Pandas or numpy series so you need to have a Series class to use that method. So most likely you want to do something like this but without a test data set it's hard to know.
df['Colour'] = df['Count'].apply(lambda x: 'Red' if x <=500 else 'Green')
Creating a test dataset shows you how this works all together:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,1000,size=(10, 4)), columns=list('ABCD'))
df['Colour'] = df['A'].apply(lambda x: 'Red' if x <=500 else 'Green')
df.head()
Which returns:
A B C D Colour
0 223 360 133 285 Red
1 300 125 642 238 Red
2 118 293 442 382 Red
3 448 357 55 124 Red
4 995 395 658 559 Green
If you want to use .loc to access the whole column you can use df.loc[:, 'Count'] You can read more about the .loc method here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With