Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I have to create a categorical variable out of pandas date-time index and looking for a Pythonic way for it.

Till now i just looped through all index and did a bunch of if-else. I tried using, taking inspiration from (Adding a new pandas column with mapped value from a dictionary), a dictionary of lambda if else function and use map for creating a categorical function, but it didn't work

date_series = pd.date_range(start = '2010-12-31', end = '2018-12-31', freq = 'M')

regime_splitter = {lambda x : x < '2012' : 'before 2012' , lambda x : x>= '2012' and x < '2014': '2012 - 2014', lambda x : x>= '2014' : 'after 2014'}

date_series.map(regime_splitter)

expected result

         date              regime

0  2010-12-31         before 2012

1  2013-05-31  between 2012, 2014

2  2018-12-31          after 2014

1 Answer

0 votes
by (25.1k points)

You can use numpy.select

import numpy as np

answer = np.select([x <= 2012, x>= 2014], ['before 2012','after 2014'], '2012 - 2014')

Browse Categories

...