【问题标题】:How do i slice pandas Series with DatetimeIndex and put it in a DataFrame by rows?如何使用 DatetimeIndex 对 pandas Series 进行切片并将其按行放入 DataFrame 中?
【发布时间】:2016-10-31 03:41:05
【问题描述】:

我有带有 DatetimeIndex 的 pandas Series 对象:

2016-01-04 00:00:00    11.6
2016-01-04 01:00:00    11.7
2016-01-04 02:00:00    17.1
2016-01-04 03:00:00    36.5
2016-01-04 04:00:00    19.0
2016-01-04 05:00:00     7.5
2016-01-04 06:00:00    18.7
2016-01-04 07:00:00    14.5
2016-01-04 08:00:00     6.5
2016-01-04 09:00:00    41.9
2016-01-04 10:00:00    37.3
2016-01-04 11:00:00    30.3
2016-01-04 12:00:00    38.4
2016-01-04 13:00:00    26.0
2016-01-04 14:00:00    31.0
2016-01-04 15:00:00    32.3
2016-01-04 16:00:00    29.4
2016-01-04 17:00:00    43.5
2016-01-04 18:00:00    26.9
2016-01-04 19:00:00    20.4
2016-01-04 20:00:00    16.5
2016-01-04 21:00:00    10.9
2016-01-04 22:00:00    12.8
2016-01-04 23:00:00    16.4
2016-01-05 00:00:00    10.1
2016-01-05 01:00:00     9.4
2016-01-05 02:00:00    12.0
2016-01-05 03:00:00     8.6
2016-01-05 04:00:00    16.9
2016-01-05 05:00:00     8.4
...

我如何按日期对这个系列进行切片并将其放入日期/小时 pandas Dataframes 中,如下所示:

              00   01   02   03   04 ...   22   23    
2016-01-04  11.6  1.7 17.1 36.5 19.0 ... 12.8 16.4
2016-01-05  10.1  9.4 12.0  8.6 16.9 ... 12.8 16.4
...

PS:对不起我的英语

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    首先使用to_frame 将您的系列转换为数据框,然后使用s.index.strftime('%H')index.date 提取小时和日期。最后以这些列为中心以转换为“宽”格式:

    df = s.to_frame()
    df['hour'] = df.index.strftime('%H')
    df['date'] = df.index.date
    df2 = df.pivot(columns='hour', index='date')
    

    【讨论】:

    • 感谢您的回复,但我得到了这张表(截图)link。我想我的索引系列有问题。我说的对吗?
    • 对我来说看起来不错...有什么问题?
    • 每个小时应该是一个单独的列,但现在每个小时都是一行
    • 不,这只是一个中间步骤,最后的pivot 应该将行转换为列
    • @ПетрВладимирович, df.pivot() - 不改变原始 DF,它返回一个旋转的 DF,所以你可以这样做:df = s.to_frame('val'); pivoted_df = df.assign(dt=df.index.date, hr=df.index.strftime('%H')).pivot_table(index='dt', columns='hr', aggfunc='sum', fill_value=0)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2012-08-06
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多