1

Why am i getting SettingWithCopyWarning in this code? I know that when defining a new Dataframe, i need to use .copy(), but that doesn't help.

   def calc_quantity(input_df):
        when = input_df['SecurityId'].str.endswith(
            'TMS') | input_df['SecurityId'].str.endswith('TDS')
        input_df['Quantity'] = input_df['Quantity'].fillna(0).astype(float)
        input_df['Quantity'].loc[when] *= 100
            'TMS') | input_df['SecurityId'].str.endswith('TDS').copy()
        input_df['Quantity'] = input_df['Quantity'].fillna(0).astype(float).copy()
        input_df['Quantity'].loc[when] = input_df['Quantity'].loc[when]*100
        return input_df['Quantity']
zeratul314
  • 93
  • 1
  • 7
  • 1
    This is because `input_df` is already subselection of the original dataframe. So wherever you filter input_df, you need to add `.copy` – Erfan Apr 20 '22 at 19:58
  • I've changed to ```def calc_quantity(input_df): when = input_df['SecurityId'].str.endswith( 'TMS') | input_df['SecurityId'].str.endswith('TDS').copy() input_df['Quantity'] = input_df['Quantity'].fillna(0).astype(float).copy() input_df['Quantity'].loc[when] = input_df['Quantity'].loc[when].copy()*100 return input_df['Quantity'] ``` but got some warning – zeratul314 Apr 20 '22 at 20:28
  • put it in question - it will be more readable and more people will see it. – furas Apr 20 '22 at 23:02
  • 1
    always put full error message (starting at word "Traceback") in question (not in comments) as text (not screenshot, not link to external portal). There are other useful information. – furas Apr 20 '22 at 23:03
  • put it in question-Done – zeratul314 Apr 21 '22 at 07:21

1 Answers1

1

The warning typically is a result of chained assignments and you can read more about it in this answer and this blog post also goes into great detail.

If you wish to turn it off, you can use:

pd.options.mode.chained_assignment = None
greco
  • 304
  • 4
  • 11