truth value of a Series is ambiguous


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

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.

With guidance from commentors, i have achieve my desired result! This is the code that works and i want to share it with people who faced problem too!

def  cate_shop (shop):
    if shop<4:
        return 'Service'


    if shop>=4 and shop< 140:
        return 'Food & Beverage'
    if shop>=140 and shop< 173:
        return 'Fashion'
    if shop>=173 and shop<197:
        return 'Electronics'

return ‘Other’

Asked By: Bee



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'
        return 'Other'

df['category'] =
>>> 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
Answered By: mosc9575
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.