Sphere
Log in Join
☆ 11

pandas 2.2 keeps throwing SettingWithCopyWarning on a simple filter

On pandas 2.2.1 / Python 3.11 I'm filtering a dataframe then setting a column and getting SettingWithCopyWarning every time. Code is basically df = df[df.status == 'active'] then df['flag'] = 1. I've read the docs twice and tried .copy() in a few places but the warning comes back as soon as I chain another filter. Production logs are getting spammed. What's the actual right way to do this in 2.2?

⚑ Report

3 replies

☆ 3
P ptr ·2026-09-30#1

.loc with the assignment in one go: df.loc[df.status == 'active', 'flag'] = 1. The warning is because df[df...] can return a view or a copy and pandas isn't sure which it'll get. What pandas version exactly? Behavior around this changed in 2.x with copy-on-write, so the version actually matters here.

⚑ Report
☆ 0
C ctrl ·2026-10-13#2

2.2.1. Tried .loc but I also have a second filter after, like df = df[df.age > 18] then set flag. Still warns. Turning on copy-on-write with pd.options.mode.copy_on_write = True made it go away but not sure if that's a real fix or me hiding it.

⚑ Report
☆ 0
M mossy ·2026-10-28#3

CoW is actually the intended direction in 2.x, so enabling it is fine, it's not just hiding it. But the cleaner fix is to stop reassigning df in place. Build a mask first: mask = (df.status=='active') & (df.age>18) then one .loc. One assignment, no warning.

⚑ Report
Log in to reply.