w3resource

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

 

Python Pandas: Data Series Exercise-29 with Solution

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]

Python 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 Python skills with w3resource's quiz



Python: Tips of the Day

Python: Membership Testing in a Collection

>>> a = ('one', 'two', 'three', 'four', 'five')
>>> if 'one' in a:
...     print('The tuple contains one.')
... 
The tuple contains one.
>>> b = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> if 2 in b.keys():
...     print('The dict has the key of 2.')
... 
The dict has the key of 2.