Home > Software design >  Try using .loc[row_indexer,col_indexer] error even after using .loc
Try using .loc[row_indexer,col_indexer] error even after using .loc

Time:07-07

I am simply trying to multiply two columns of a dataframe and save the results into a new column like this,

df.loc[:,'sales'] = df['Quantity']*df['UnitPrice']

I am getting the following error even though I am using .loc for the new column! Any idea what I am missing?

/var/folders/qp/lp_5yt3s65q_pj__6v_kdvnh0000gn/T/ipykernel_39035/1010072081.py:3: 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
  df.loc[:,'sales'] = df['Quantity']*df['UnitPrice']

CodePudding user response:

I expect this to work for you:

df.assign(sales=lambda df: df.Quantity * df.UnitPrice)

CodePudding user response:

Thanks for the comments. Like what @Quang Hoang mentioned, this is because I was forgetting to use .copy() to created this smaller DataFrame earlier in the code.

  • Related