簡體   English   中英

使用日期時間索引將日期/小時數據幀拆分為單列 - python,pandas

[英]unstack date/hour dataframe into single column with datetime index - python, pandas

我有一個數據框,如:

                  0       1       2       3       4       5       6       7       8       9       10    11       12      13      14      15      16      17      18      19      20      21      22      23
    16.01.2018  25.45   24.99   24.68   25.00   26.19   28.96   35.78   44.66   41.75   41.58   41.48   41.66   40.66   40.39   40.33   40.73   41.58   45.06   45.84   42.69   39.56   35.4    33.27   29.49
    17.01.2018  28.78   27.71   26.55   25.76   25.97   26.97   30.89   36.06   41.24   40.67   39.86   39.42   38.17   37.31   36.58   36.78   37.8    40.78   40.8    38.95   34.34   31.95   31.56   29.26

其中索引是某個值發生的日期,而列(從 0 到 23)表示小時。 我想拆開數據框以獲得日期時間索引和具有相應值的單列:

    16.01.2018 00:00:00  25.45
    16.01.2018 01:00:00  24.99
    16.01.2018 02:00:00  25.68
    16.01.2018 03:00:00  25.00
....

目前我正在做:

index = pd.date_range(start = df.index[0], periods=len(df.unstack()), freq='H')
new_df = pd.DataFrame(index=index)
for d in new_df.index.date:
    for h in new_df.index.hour:
        new_df['value'] = df.unstack()[h][d]

但是 for 循環需要很長時間......你有更好(更快)的解決方案嗎?

將 index 轉換為DatetimeIndex並將列轉換為timedelta s,因此在通過DataFrame.stackSeries.reset_index重塑后,只對兩個新列求和:

df.index = pd.to_datetime(df.index)
df.columns = pd.to_timedelta(df.columns + ':00:00')
df = df.stack().reset_index(name='data')
df.index = df.pop('level_0') + df.pop('level_1')
print (df.head())
                      data
2018-01-16 00:00:00  25.45
2018-01-16 01:00:00  24.99
2018-01-16 02:00:00  24.68
2018-01-16 03:00:00  25.00
2018-01-16 04:00:00  26.19

Soluton與unstack是類似的,只是輸出順序是不同的:

df.index = pd.to_datetime(df.index)
df.columns = pd.to_timedelta(df.columns + ':00:00')
df = df.unstack().reset_index(name='data')
df.index = df.pop('level_1') + df.pop('level_0')
print (df.head())
                      data
2018-01-16 00:00:00  25.45
2018-01-17 00:00:00  28.78
2018-01-16 01:00:00  24.99
2018-01-17 01:00:00  27.71
2018-01-16 02:00:00  24.68

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM