Good morning.
My problem is the following: I have a pandas dataframe with a column named 'fecha' that stores date objects and a list of tuples that stores an initial datetime and a final datetime. Show examples below:
df =
fecha
0 2018-10-01
1 2019-01-12
2 2018-12-25
list_ranges = [(datetime.datetime(2018, 10, 1, 0, 0),
datetime.datetime(2018, 10, 15, 0, 0)),
(datetime.datetime(2018, 10, 16, 0, 0),
datetime.datetime(2018, 10, 31, 0, 0)),
(datetime.datetime(2018, 11, 1, 0, 0), datetime.datetime(2018, 11, 15, 0, 0)),
(datetime.datetime(2018, 11, 16, 0, 0),
datetime.datetime(2018, 11, 30, 0, 0)),
(datetime.datetime(2018, 12, 1, 0, 0), datetime.datetime(2018, 12, 15, 0, 0)),
(datetime.datetime(2018, 12, 16, 0, 0),
datetime.datetime(2018, 12, 31, 0, 0)),
(datetime.datetime(2019, 1, 1, 0, 0), datetime.datetime(2019, 1, 15, 0, 0))]
and I want to get the position of the range in which each date is on the list. The result I'm looking for is:
df =
result
0 1
1 7
2 6
Currently, I'm doing this:
df.fecha = df.fecha.apply(lambda x: select_quincena(x, quincenas))
def select_quincena(fecha, quincenas):
fecha = datetime.datetime.combine(fecha, datetime.datetime.min.time())
num = 0
for e in quincenas:
num += 1
if fecha >= e[0] and fecha <= e[1]:
return num
It's working fine, but I'm pretty sure that there is a better and easier way to do this.
Thanks you very much in advance.