Alec Deason Alec Deason - 4 months ago 11
Python Question

Assignment through chained indexers

I would like to be able to assign to a DataFrame through chained indexers. Notionally like this:

subset = df.loc[mask]
... # much later
subset.loc[mask2, 'column'] += value


This does not work because, as I understand it, the second .loc triggers a copy-on-write. Is there a way to do this?

I could pass
df
and
mask
around so that the later code could combine
mask
and
mask2
before making an assignment but it feels much cleaner to be able to pass around the
subset
view instead so that the later code only has to worry about it's own mask.

Answer

When you get to:

subset.loc[mask2, 'column']

assign this to another subset so you can access its index and columns attributes.

subsubset = subset.loc[mask2, 'column']

Then you can access df with subsubset's index and columns

df.loc[subsubset.index, subsubset.columns] += 1