0

I have the following operation over a Pandas DataFrame in my Python script:

a['tier_diff'] = a['tier_rate'].diff()
discontinuity = a.loc[a['tier_diff'] > 1]

which causes the following warning message:

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

I followed this answer aiming to avoid it, getting the code like this:

a.loc['tier_diff'] = a['tier_rate'].diff()
discontinuity = a.loc[a['tier_diff'] > 1]

but now I get this error: KeyError: 'tier_diff'

Can't find what I missed applying the answer

HuLu ViCa
  • 5,077
  • 10
  • 43
  • 93
  • minus 1, no traceback, no example data, wrongly followed answer –  Nov 26 '21 at 15:30
  • discontinuity = a.loc[a['tier_diff'] > 1].copy() – BENY Nov 26 '21 at 15:51
  • `a['tier_diff'] = a['tier_rate'].diff()` is the problem. Your `a` is a slice of a bigger dataframe, and you can't just modify `a`. so `discontinuity = a.assign(tier_diff=lambda x: x['tier_rate'].diff())` helps as `assign` works on a copy. – Quang Hoang Nov 26 '21 at 15:58

0 Answers0