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?

2
  • 1
    How have you defined Transactions_Meat earlier in your code. Is it a slice of another dataframe? Commented Oct 2, 2018 at 9:46
  • @jpp I've edited according to your question Commented Oct 2, 2018 at 9:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This will indeed remove the warning. But as mentioned in the stackoverflow-answer (stackoverflow.com/questions/31468176/…), copy() is not the proper way.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.