Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How (improve) updating multiple columns of a pandas dataframe, when the columns are datetime?

I have a DataFrame that has columns as datetime objects, and I would like to update specific values for a specific index based on a list of days.

Here is an MRE that works:

import pandas as pd
start, stop = "2023-12-01", "2023-12-31"
dates: pd.Index =  pd.date_range(start, stop, freq="D")
december = pd.DataFrame(columns = dates, index = ['ft', 'pt'])
december.loc['ft', pd.to_datetime(['2023-12-04', '2023-12-06', '2023-12-11', '2023-12-12', '2023-12-27', '2023-12-28'])] = 'X'

In this example, I update the columns for the following dates:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['2023-12-04', '2023-12-06', '2023-12-11', '2023-12-12', '2023-12-27', '2023-12-28']

But ideally I would pass a list of days like [4, 6, 11, 12, 27, 28] to the .loc call.

>Solution :

Just do that using the day attribute and isin:

december.loc['ft', december.columns.day.isin([4, 6, 11, 12, 27, 28])] = 'X'

If you also only want to target december (or a list of months):

december.loc['ft', (december.columns.day.isin([4, 6, 11, 12, 27, 28])
                   &december.columns.month.isin([12])
                   )] = 'X'

Output:

   2023-12-01 2023-12-02 2023-12-03 2023-12-04 2023-12-05 2023-12-06 2023-12-07 2023-12-08 2023-12-09 2023-12-10 2023-12-11 2023-12-12 2023-12-13 2023-12-14 2023-12-15 2023-12-16 2023-12-17 2023-12-18 2023-12-19 2023-12-20 2023-12-21 2023-12-22 2023-12-23 2023-12-24 2023-12-25 2023-12-26 2023-12-27 2023-12-28 2023-12-29 2023-12-30 2023-12-31
ft        NaN        NaN        NaN          X        NaN          X        NaN        NaN        NaN        NaN          X          X        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN          X          X        NaN        NaN        NaN
pt        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN        NaN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading