0x1 0x1 - 26 days ago 14
Python Question

How to change the row values based on the range of the index in pandas?

I have a dataset like this:

index _id first last date
0 11 John Doe 2016-01-01
1 12 Jane Doe 2016-01-06
2 13 Jack Hammer 2016-01-06
3 14 Peter Dex 2016-01-10


I want to change the date from
2016-01-06
to
2016-01-10
based on the range of the index(1-2 in this case). How can I do that?

Thanks!

Answer Source

Is there any involved logic or methodology behind this? If not, you can just access that slice using df.loc:

In [354]: df.loc[df.index.isin([1, 2]), 'date'] = '2016-01-10'

In [355]: df
Out[355]: 
   index  _id  first    last        date
0      0   11   John     Doe  2016-01-01
1      1   12   Jane     Doe  2016-01-10
2      2   13   Jack  Hammer  2016-01-10
3      3   14  Peter     Dex  2016-01-10

You can substitute [1, 2] with a range object:

df.loc[df.index.isin(range(1, 3)), 'date'] = '2016-01-10'