0

I am having trouble identifying a solution that avoids flagging a warning when performing arithmetic functions on a Pandas DataFrame.

My DataFrame looks like this:

   A   B  
0  3   2 
1  6   6 
2  12  7 

And the arithmetic function I am using is:

df['C'] = (df['A'] * df['B']) - (1.5*df['B'])         

Producing:

   A   B  C
0  3   2  3
1  6   6  27
2  12  7  73.5

This function works, but a warning is flagged that says:

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

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

I've tried a few things, such as: df.loc[:,['A', 'B']] = df.loc[:,['A', 'B']].multiply(df.loc[:, 'C'], axis=1)

But I would really like to find an efficient solution to achieve this in one step like I had previously. I know I can just silence the warning, but I know if I find a solution using .loc, the code will be faster.

lcfields
  • 83
  • 6
  • please see Mikulas' answer down there. In short: If `df` is a subset of another frame (or even itself) and you plan to do modifications on it, better is to chain a .copy() at the end of its definition, i.e., `df = some_frame[...].copy()`. This explicitly makes a copy, no warnings needed. – Mustafa Aydın Jan 27 '23 at 17:25

0 Answers0