Python Pandas: Get the day of month, year, week, week number
Python Pandas: Data Series Exercise-28 with Solution
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.
Sample Solution :
Python Code :
import pandas as pd from dateutil.parser import parse date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20']) print("Original Series:") print(date_series) date_series = date_series.map(lambda x: parse(x)) print("Day of month:") print(date_series.dt.day.tolist()) print("Day of year:") print(date_series.dt.dayofyear.tolist()) print("Week number:") print(date_series.dt.weekofyear.tolist()) print("Day of week:") print(date_series.dt.weekday_name.tolist())
Original Series: 0 01 Jan 2015 1 10-02-2016 2 20180307 3 2014/05/06 4 2016-04-12 5 2019-04-06T11:20 dtype: object Day of month: [1, 2, 7, 6, 12, 6] Day of year: [1, 276, 66, 126, 103, 96] Week number: [1, 39, 10, 19, 15, 14] Day of week: ['Thursday', 'Sunday', 'Wednesday', 'Tuesday', 'Tuesday', 'Saturday']
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Python: Cache results with decorators
There is a great way to cache functions with decorators in Python. Caching will help save time and precious resources when there is an expensive function at hand.
Implementation is easy, just import lru_cache from functools library and decorate your function using @lru_cache.
from functools import lru_cache @lru_cache(maxsize=None) def fibo(a): if a <= 1: return a else: return fibo(a-1) + fibo(a-2) for i in range(20): print(fibo(i), end="|") print("\n\n", fibo.cache_info())
0|1|1|2|3|5|8|13|21|34|55|89|144|233|377|610|987|1597|2584|4181| CacheInfo(hits=36, misses=20, maxsize=None, currsize=20)
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework