behappy behappy - 6 months ago 25
Python Question

Python: pandas dataframe condition for slice of a dataframe

I want to change the content in a slice of the pandas dataframe column that has 'ABC' ONLY in the column if the condition is fulfill.
I try the code as below but it return this error


A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value instead



print df

Item Price Quantity
0 ABC 10 30
1 ABB 20 50
2 ABC 37 89
3 ABG 5 78

con1 = df['Price']>10
con2 = df['Quantity']>20
df[df['Item']=='ABC'].loc[con1 & con2,'Item'] = 'ABCD'

Output that I want

Item Price Quantity
0 ABC 10 30
1 ABB 20 50
2 ABCD 37 89
3 ABG 5 78

Answer Source

The warning is caused by the chained indexing (first making a slice and then using .loc on that slice). df['Item']=='ABC' is just another condition that you can use in .loc:

df.loc[con1 & con2 & (df['Item']=='ABC'), 'Item'] = 'ABCD'