Reputation: 562
I need to know how many reservations stay by room type. I have this DataFrame with the start and the end of each reservation and its room type:
date_from date_to room_type
0 2017-08-07 2017-08-12 SUI
1 2017-08-09 2017-08-11 TWN
2 2017-08-09 2017-08-11 QUA
3 2017-08-07 2017-08-11 QUA
4 2017-08-09 2017-08-11 QUA
5 2017-08-09 2017-08-11 QUA
6 2017-08-09 2017-08-11 DBL
7 2017-08-08 2017-08-11 FAM
8 2017-08-08 2017-08-16 INDP
9 2017-08-09 2017-08-11 QUA
I need something like this:
stay_date room_type
0 2017-08-07 SUI
1 2017-08-08 SUI
2 2017-08-09 SUI
3 2017-08-10 SUI
4 2017-08-11 SUI
5 2017-08-09 TWN
5 2017-08-10 TWN
...
So, I can create a pivot table like this:
df = df.pivot_table(
values=['room_type'],
index='stay_date',
aggfunc=len
)
and return it something like that:
room_type__code DBL FAM SUI TRP TWIN
stay_date
2017-07-01 61 20 9 19 39
2017-07-02 49 10 7 11 28
2017-07-03 61 14 4 14 40
2017-07-04 65 13 2 11 37
2017-07-05 66 17 2 11 38
Upvotes: 1
Views: 1864
Reputation: 863331
Use itertuples
and date_range
with frequency D
with concat
for creating new expanding DataFrame
:
#convert to datetime if necessary
df['date_from'] = pd.to_datetime(df['date_from'])
#remove one day from to date
df['date_to'] = pd.to_datetime(df['date_to']) - pd.Timedelta(1, unit='d')
df1 = pd.concat([pd.Series(r.room_type,
pd.date_range(r.date_from, r.date_to, freq='D'))
for r in df.itertuples()]) \
.reset_index()
df1.columns = ['stay_date','room_type']
print (df1)
stay_date room_type
0 2017-08-07 SUI
1 2017-08-08 SUI
2 2017-08-09 SUI
3 2017-08-10 SUI
4 2017-08-11 SUI
5 2017-08-09 TWN
6 2017-08-10 TWN
7 2017-08-09 QUA
8 2017-08-10 QUA
9 2017-08-07 QUA
10 2017-08-08 QUA
11 2017-08-09 QUA
12 2017-08-10 QUA
13 2017-08-09 QUA
...
...
Upvotes: 4