Skip to content Skip to sidebar Skip to footer

Python - Duplicate Rows X Number Of Times Based On A Value In A Column

I have a pandas dataframe of bookings at a hotel. Each row is a booking, like this: Name Arrival Departure RoomNights Trent Cotchin 29/10/2017 2/11/2017

Solution 1:

Use:

#convert columns to datetime
df['Arrival'] = pd.to_datetime(df['Arrival'])
df['Departure'] = pd.to_datetime(df['Departure'])

#repeat rows
df = df.loc[df.index.repeat(df['RoomNights'])]
#group by index with transform for date ranges
df['RoomNight Date'] =(df.groupby(level=0)['Arrival']
                         .transform(lambda x: pd.date_range(start=x.iat[0], periods=len(x))))
#unique default index
df = df.reset_index(drop=True)
print (df)
            Name    Arrival  Departure  RoomNights RoomNight Date
0  Trent Cotchin 2017-10-29 2017-11-02           4     2017-10-29
1  Trent Cotchin 2017-10-29 2017-11-02           4     2017-10-30
2  Trent Cotchin 2017-10-29 2017-11-02           4     2017-10-31
3  Trent Cotchin 2017-10-29 2017-11-02           4     2017-11-01
4  Dustin Martin 2017-11-01 2017-11-04           3     2017-11-01
5  Dustin Martin 2017-11-01 2017-11-04           3     2017-11-02
6  Dustin Martin 2017-11-01 2017-11-04           3     2017-11-03
7     Alex Rance 2017-11-02 2017-11-03           1     2017-11-02

Post a Comment for "Python - Duplicate Rows X Number Of Times Based On A Value In A Column"