jeudi 19 avril 2018

Python Pandas if statement based on numeric and string condistions

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

Aucun commentaire:

Enregistrer un commentaire