Search code examples
python-3.xpandaspandas-loc

Error while trying to define a function to create price bucket for apps


I have an csv data set that I imported in Jupyter and stored under inp0. I'm trying to create price bucket for these using .loc function in pandas bet getting below error.

My Code:

inp0.loc[inp0.price==0.00, 'Price_Bucket'] = 'Free App'
inp0.loc[[inp0.price>0.00 and inp0.price<3.00],'Price_Bucket'] = 'Apps that cost <3'
inp0.loc[[inp0.price>=3.00 and inp0.price<5.00],'Price_Bucket'] = 'Apps that cost <5'
inp0.loc[inp0.price>=5.00,'Price_Bucket'] = 'Apps that cost >=5'
inp0.price_bucket.value_counts()

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How do I resolve it?


Solution

  • Try with np.where which works like if else in columns/vectors:

    import numpy as np
    inp0['Price_Bucket'] = np.where(inp0['price']==0.00, 'Free App', np.where(inp0['price']<3.00, 'Apps that cost <3', np.where(inp0['price']<5.00, 'Apps that cost <5', 'Apps that cost >=5')))