pandas python - 基于列中的值重复行 x 次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46659378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:36:41  来源:igfitidea点击:

python - Duplicate rows x number of times based on a value in a column

pythonpandas

提问by Ben Sharkey

I have a pandas dataframe of bookings at a hotel. Each row is a booking, like this:

我有一个酒店预订的Pandas数据框。每一行都是一个预订,像这样:

Name             Arrival       Departure     RoomNights
Trent Cotchin    29/10/2017    2/11/2017     4
Dustin Martin    1/11/2017     4/11/2017     3
Alex Rance       2/11/2017     3/11/2017     1

I want to use python to convert so that each row becomes a roomnight. The output would look like this:

我想使用python进行转换,以便每一行都变成一个房间。输出将如下所示:

Name             Arrival       Departure     RoomNights   RoomNight Date
Trent Cotchin    29/10/2017    2/11/2017     4            29/10/2017
Trent Cotchin    29/10/2017    2/11/2017     4            30/10/2017
Trent Cotchin    29/10/2017    2/11/2017     4            31/10/2017
Trent Cotchin    29/10/2017    2/11/2017     4            1/11/2017
Dustin Martin    1/11/2017     4/11/2017     3            1/11/2017
Dustin Martin    1/11/2017     4/11/2017     3            2/11/2017
Dustin Martin    1/11/2017     4/11/2017     3            3/11/2017
Alex Rance       2/11/2017     3/11/2017     1            2/11/2017

This allows me to easily sum the total number of roomnights for any given day/month.

这使我可以轻松地总结任何给定日/月的房晚总数。

回答by jezrael

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