-1

Working with the dataframe df:

ID | Category | Price
23      A       101
34      B       50
24      A       55

I want to add a flag, for all Category A and Price less and equal to 100.

This is my code:

df['Flag'][(df['Price'] <=100)&(df['Category']=='A')] = 'X'

I get this error:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

When I try to filter on the flag, I get this error:

df.loc[df['Flag'] == 'X']

TypeError: invalid type comparison

Expected Output:

ID | Category | Price  Flag
23      A       101     
34      B       50
24      A       55       X
jeangelj
  • 4,338
  • 16
  • 54
  • 98
  • 2
    Possible duplicate of [How to deal with SettingWithCopyWarning in Pandas?](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas) – ASGM Apr 19 '18 at 18:28

2 Answers2

1

Use loc

df.loc[(df['Price'] <=100)&(df['Category']=='A'), "Flag"] = 'X'
rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

You could use map():

>>> df['flag'] = ((df['Category'] == 'A') & (df['Price'] <= 100)).map({True: 'X', False: ''})
>>> df
   ID Category  Price flag
0  23        A    101
1  34        B     50
2  24        A     55    X
user3483203
  • 50,081
  • 9
  • 65
  • 94