0

I’m trying to add a new column to my DataFrame Transactions_Meat:

   Transactions_Meat['Avg_IPrice'] = Transactions_Meat['Rev'] / Transactions_Meat['Units_Sold']

Resulting to this warning:

SettingWithCopyWarning: 
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

Transactions_Meat is a copy of a DataFrame named Transactions:

Transactions_Meat = Transactions[Transactions['Category'] == 'Meat']

So, im trying to use .loc which changed my approach to:

Transactions_Meat.loc[:,'Avg_IPrice'] = Transactions_Meat['Rev'] / Transactions_Meat['Units_Sold']

Unfortunately, I’m still getting the same warning. I've visited the documentation of pandas as described here. I also checked the stackoverflow-question which is already handling this problem. But I couldn’t get rid of the warning.

Any possbility to remove the warning using the DataFrame.loc method?

Justin Lange
  • 897
  • 10
  • 25

1 Answers1

0

This line is ambiguous:

Transactions_Meat = Transactions[Transactions['Category'] == 'Meat']

If you want a copy, be explicit and use pd.DataFrame.copy:

Transactions_Meat = Transactions[Transactions['Category'] == 'Meat'].copy()

This should remove the subsequent warnings, as well as guarantee that you original Transactions dataframe will not be modified when you manipulate Transactions_Meat.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • This will indeed remove the warning. But as mentioned in the stackoverflow-answer (https://stackoverflow.com/questions/31468176/setting-values-on-a-copy-of-a-slice-from-a-dataframe?rq=1), copy() is not the proper way. – Justin Lange Oct 02 '18 at 10:00
  • 1
    @JustinScofield, The question there is different. Here you **want** a copy. In that question, OP does not want a copy and therefore `copy()` is inappropriate. – jpp Oct 02 '18 at 10:04