w3resource

Pandas Data Series: Convert year-month string to dates adding a specified day of the month

 


Write a Pandas program to convert year-month string to dates adding a specified day of the month.

Sample Solution :

Python Code :

import pandas as pd
from dateutil.parser import parse
date_series = pd.Series(['Jan 2015', 'Feb 2016', 'Mar 2017', 'Apr 2018', 'May 2019'])
print("Original Series:")
print(date_series)
print("\nNew dates:")
result = date_series.map(lambda d: parse('11 ' + d))
print(result)

Sample Output:

Original Series:
0    Jan 2015
1    Feb 2016
2    Mar 2017
3    Apr 2018
4    May 2019
dtype: object

New dates:
0   2015-01-11
1   2016-02-11
2   2017-03-11
3   2018-04-11
4   2019-05-11
dtype: datetime64[ns]

Explanation:

In the above exercise -

date_series = pd.Series(['Jan 2015', 'Feb 2016', 'Mar 2017', 'Apr 2018', 'May 2019']): This line creates a Pandas Series object 'date_series' containing five strings representing months and years in the format "MMM YYYY", where MMM is the three-letter abbreviation for the month.

result = date_series.map(lambda d: parse('11 ' + d)): This code applies the map() method to the Pandas Series object 'date_series' and a lambda function to parse each string into a Pandas Timestamp object using the dateutil.parser.parse() method.

The lambda function prepends the string "11 " to each input string, effectively adding a day value of 11 to each month-year string. This is necessary because parse() expects a day value in the input string.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to get the day of month, day of year, week number and day of week from a given series of date strings.
Next: Write a Pandas program to filter words from a given series that contain atleast two vowels.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.