I am trying to create new column in pandas dataframe with row number as condition using iloc.
This is my code:
import pandas as pd
shop=pd.DataFrame.from_dict(data)
def cate_shop (shop):
if shop==shop.iloc[:4]:
return 'Service'
if shop==shop.iloc[4:140]:
return 'Food & Beverage'
if shop==shop.iloc[140:173]:
return 'Fashion'
if shop==shop.iloc[173:197]:
return 'Electronics'
return 'Other'
shop['category']=shop.apply(lambda shop: cate_shop(shop), axis=1)
Appreciate any guidance as i have no idea what went wrong.
Are you looking for a option to map
the number of the index to a value?
Hope this snipped helps:
import pandas as pd
df = pd.DataFrame({'values':list(range(10))})
def f(x):
if x < 4:
return 'Service'
elif x < 6:
return 'Food & Beverage'
else:
return 'Other'
df['category'] = df.index.map(f)
>>> df
values category
0 0 Service
1 1 Service
2 2 Service
3 3 Service
4 4 Food & Beverage
5 5 Food & Beverage
6 6 Other
7 7 Other
8 8 Other
9 9 Other