gpt4 book ai didi

python - 每天在两列范围之间的数据框中添加行

转载 作者:行者123 更新时间:2023-11-30 22:32:00 25 4
gpt4 key购买 nike

我需要知道按房型划分的预订数量。我有这个 DataFrame,其中包含每个预订的开始和结束及其房间类型:

    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

我需要这样的东西:

    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
...

所以,我可以创建一个像这样的数据透视表:

df = df.pivot_table(
values=['room_type'],
index='stay_date',
aggfunc=len
)

并返回类似的内容:

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

最佳答案

使用itertuplesdate_range频率 Dconcat用于创建新的扩展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
...
...

关于python - 每天在两列范围之间的数据框中添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45630026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com