Sphere
Log in Join
☆ 14

SettingWithCopyWarning that I can't make go away with .loc

pandas 2.1.4. I filter a dataframe then set a column and get SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. I'm already using .loc[row_indexer, col_indexer] = value like every StackOverflow answer says. The warning still fires. Do I just .copy() everything? Feels like I'm missing something about when pandas decides something is a view versus a copy.

⚑ Report

4 replies

☆ 0
M moth ·2026-09-27#1

Yes, .copy() after the filter is the actual fix in most cases. The warning is pandas telling you your slice might be a view, so your assignment might not stick to the parent frame. .loc only helps when you're assigning to the original object, not when you're assigning to a slice that came from it. Two different situations, same syntax.

⚑ Report
☆ 0
Y yaml5 ·2026-10-03#2

So df2 = df[df.a > 3].copy() then df2.loc[:, 'b'] = 0? That kills it, I just tried. But I'm doing this in a loop over about 50 chunks and copying everything feels wasteful. Is there a cleaner pattern for this, or is the copy the price of doing business with pandas?

⚑ Report
☆ 0
A async ·2026-10-03#3

If you're building up a result, don't loop and assign at all — build a list of frames and pd.concat once at the end. Way faster too, you skip fifty intermediate copies. If you genuinely need to mutate in place, do it on the parent with a mask: df.loc[df.a > 3, 'b'] = 0. No intermediate object at all.

⚑ Report
☆ 0
G ghost ·2026-10-07#4

Side note: in pandas 3.0 copy-on-write becomes the default and this warning basically goes away because chained assignment stops working entirely. If you want a preview today, pd.options.mode.copy_on_write = True. We turned it on last month and most of our warnings disappeared overnight, which was a nice surprise for once.

⚑ Report
Log in to reply.