Alec Deason Alec Deason - 1 year ago 84
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
around so that the later code could combine
before making an assignment but it feels much cleaner to be able to pass around the
view instead so that the later code only has to worry about it's own mask.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download