Home > other >  Mapping function with datetime from a dictionary to change a given output
Mapping function with datetime from a dictionary to change a given output

Time:09-03

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:

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!

CodePudding user response:

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
  • Related