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

Mapping function with datetime from a dictionary to change a given output

Context: I’d like to use a dictionary to map datetime to change the extracted years according to the pair of key:values on a given dictionary. Here’s a quick example:

Let’s say we have a dataframe with datetime:

       Week
1   2019-06-10
2   2019-06-17
3   2019-06-24
4   2019-07-01

And we extract the year from this as such:

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

test['year'] = test['Week'].dt.year.astype(str) 

Resulting in this:

       Weelk    year
1   2019-06-10  2019
2   2019-06-17  2019
3   2019-06-24  2019
4   2019-07-01  2019

Desired Output: How could I make it so that when passing this dictionary:

date_mapping = {
    '2019-12-30':'2020',
    '2021-01-04':'2021',
    '2022-01-03':'2022'
}

I can "grab" the keys of the dictionary and if the datetime is 2019-12-30, for example, the year column would be changed to 2020 instead of 2019?

The output after mapping this dictionary would look like this:

       Week     year
1   2019-06-10  2019
2   2019-06-17  2019
3   2019-06-24  2019
4   2019-07-01  2019
...
30  2019-12-30  2020

Tested implementations:

I was trying to use the map function, but I keep getting NaN for the year column

test['year'] = test['Week'].map(date_mapping,test['year'])

       Week     year
1   2019-06-10  NaN
2   2019-06-17  NaN
3   2019-06-24  NaN
4   2019-07-01  NaN

Do I need to convert the datestrings to dt or anything like that? Not quite sure where to start on that

Thank you all in advance!

>Solution :

You can use df.replace

test.Week = pd.to_datetime(test.Week)

test.year = test.Week.replace({
    '2019-12-30':'2020',
    '2021-01-04':'2021',
    '2022-01-03':'2022'
}).dt.year
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