What is the best way to modify values in a slice of a column with .iloc in Pandas

5 days ago 12
ARTICLE AD BOX

With ChainedAssignmentErrors being enforced in Pandas 3.0 I was wondering what the best way to modify values in a slice of a column where the slicing is done with .iloc[] is.

For example this causes a ChainedAssignmentEror:

df = pd.DataFrame({"A": [1, 1, 1, 2, 2]}, columns=["A"]) df.iloc["A"][0:2] *= 2

The recommendation to fix this when using .loc[] is to just use df.loc[0:2,"A"]*=2 which works well. However, if I only have the row indices that I want to slice I would need to use .iloc[].

Doing this:

df.iloc[0:2,"A"] *= 2

gives a ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types.

So my question is, what is the best way of performing this operation?

Read Entire Article