Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PYTHON: Pandas datetime index range to change column values

I have a dataframe indexed using a 12hr frequency datetime:

                    id  mm ls
date            
2007-09-27 00:00:00 1   0   0
2007-09-27 12:00:00 1   0   0
2007-09-28 00:00:00 1   15  0
2007-09-28 12:00:00 NaN NaN 0
2007-09-29 00:00:00 NaN NaN 0
Timestamp('2007-09-27 00:00:00', offset='12H')

I use column 'ls' as a binary variable with default value '0' using:

data['ls'] = 0

I have a list of days in the form '2007-09-28' from which I wish to update all 'ls' values from 0 to 1.

                    id  mm ls
date            
2007-09-27 00:00:00 1   0   0
2007-09-27 12:00:00 1   0   0
2007-09-28 00:00:00 1   15  1
2007-09-28 12:00:00 NaN NaN 1
2007-09-29 00:00:00 NaN NaN 0
Timestamp('2007-09-27 00:00:00', offset='12H')

I understand how this can be done using another column variable ie:

data.ix[data.id == '1'], ['ls'] = 1

yet this does not work using datetime index. Could you let me know what the method for datetime index is?

like image 259
BenP Avatar asked Jun 05 '26 01:06

BenP


1 Answers

You have a list of days in the form '2007-09-28':

days = ['2007-09-28', ...]

then you can modify your df using:

df['ls'][pd.DatetimeIndex(df.index.date).isin(days)] = 1
like image 100
eumiro Avatar answered Jun 07 '26 15:06

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!