-3

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Bee
  • 5
  • 3
  • Welcome to Stack Overflow. Please read [ask] and note well that this is **not a discussion forum**. Please do not edit answers into the question; and please **ask a clear, specific question** when posting - we [cannot offer](https://meta.stackoverflow.com/questions/284236/) "any guidance". If a question is about an error message, do not just copy part of the error into the title; show a [complete](https://meta.stackoverflow.com/questions/359146) error message, **after** first [looking it up](https://meta.stackoverflow.com/questions/261592). – Karl Knechtel Jan 23 '23 at 14:04
  • In your own words, where the code says `if shop==shop.iloc[:4]:`, exactly what are you expecting this to mean? It seems as though you expect the `shop` on the left-hand side to mean a single cell from the Dataframe (which was passed to the `lambda`), but the `shop` on the right-hand side to mean the entire Dataframe. Do you see why that can't possibly work? – Karl Knechtel Jan 23 '23 at 14:05

1 Answers1

0

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
mosc9575
  • 5,618
  • 2
  • 9
  • 32
  • Please read [answer] and note well that this is **not a discussion forum**. The purpose of questions here **is not** to solve a problem for OP, but to help build a library of searchable questions and answers. Please only attempt to answer questions that meet standards, rather than ones that should be swiftly closed. – Karl Knechtel Jan 23 '23 at 14:07