0

The warning goes away if you slice by label (the commented line), and all my reading about the warning doesn't explain why that would be any different. I need to slice by a boolean array, so what am I supposed to do (other than ignore the warning)?

import pandas as pd

x = pd.DataFrame({'A': [0, 1], 'B': [0, 1]})
y = x.loc[[True, False], :]
# y = x.loc[[0], :]
y.loc[:, 'A'] = 1
Ian
  • 1,062
  • 1
  • 9
  • 21
  • 1
    This is a known issue. There are many inconsistencies in the behaviours of loc [No SettingWithCopyWarning for chained indexing when .loc or .iloc is first indexer](https://github.com/pandas-dev/pandas/issues/18752) this also extends to the production of copys or views. – Henry Ecker Oct 22 '21 at 01:20
  • @HenryEcker Known since 2017 and not even a PR ... that's terrifying. – Ian Oct 22 '21 at 01:41
  • A bit. However, in many ways doing the "correct" thing avoids all of these issues. Copys should always be explicit with `copy` and subsetting should always be done with `loc` or `iloc` on assignment. The problem is the inconsistencies are super confusing to finding out why things happen the way they do. I'm going to close this question with some duplicates so this can act as a sign post for others need more information about the warning and more details on how to solve it. – Henry Ecker Oct 22 '21 at 01:47

1 Answers1

-1

Adding .copy from your slice

y = x.loc[[True, False], :].copy()
y
   A  B
0  0  0
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Isn't copying a lot of overhead? My boolean array is usually all true, and the warning already doesn't happen in that case. – Ian Oct 22 '21 at 01:05