使用 pandas 拆开枢轴 table 并转换为时间戳格式

Use pandas to unstack a pivot table and convert to a timestamp format

我有下面的主元table,我想将其拆开并转换为时间戳格式

date,00:00:00,00:15:00,00:30:00,00:45:00,01:00:00,01:15:00,01:30:00,01:45:00,02:00:00
2008-01-01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0

所需的时间戳格式

wordtimestamp value
2008-01-01 00:00:00,0.0
2008-01-01,00:15:00,0.0
2008-01-01,00:30:00,0.0
2008-01-01,00:45:00,0.0
2008-01-01,01:00:00,0.0
2008-01-01,01:15:00,0.0
2008-01-01,01:30:00,0.0
2008-01-01,01:45:00,0.0
2008-01-01,02:00:00,0.0

我已尝试以下操作,但出现错误。我该如何解决这个错误,或者是否有替代解决方案来实现我的解决方案。

import pandas as pd 
import numpy as np
from datetime import datetime

def unpivot_data(date,time):
    time = datetime.strptime(time, "%H:%M:%S").time()
    full_timestamp = datetime.combine(date, time)
    return full_timestamp

if __name__ == '__main__':
    df = pd.read_csv('pivot_data.csv')

    df = df.T.unstack().reset_index()
    df['wordtimestamp'] = map(unpivot_data, df.date, df.level_1)
    df.index = df.wordtimestamp
    df = df.drop(['date','level_1','wordtimestamp'],axis=1)
    df.columns = ["value"]
    print(df)

错误

回溯(最近调用最后): 文件“pivot.py”,第 14 行,位于 df['wordtimestamp'] = map(unpivot_data, df.date, df.level_1) 文件“/home/.../.local/lib/python3.6/site-packages/pandas/core/generic.py”,第 5141 行,在 getattr 中 return object.getattribute(self, name) AttributeError: 'DataFrame' 对象没有属性 'date'

IIUC,你可以这样做:

df = pd.read_csv('pivot_data.csv', index_col=0)
# here for demo
# df = pd.read_csv(io.StringIO(data), index_col=0)

df = df.stack()
df.index = pd.to_datetime([' '.join(i) for i in df.index])

df = df.rename_axis('wordtimestamp').reset_index(name='value')

输出:

        wordtimestamp  value
0 2008-01-01 00:00:00    0.0
1 2008-01-01 00:15:00    0.0
2 2008-01-01 00:30:00    0.0
3 2008-01-01 00:45:00    0.0
4 2008-01-01 01:00:00    0.0
5 2008-01-01 01:15:00    0.0
6 2008-01-01 01:30:00    0.0
7 2008-01-01 01:45:00    0.0
8 2008-01-01 02:00:00    0.0

使用的输入:

data = '''date,00:00:00,00:15:00,00:30:00,00:45:00,01:00:00,01:15:00,01:30:00,01:45:00,02:00:00
2008-01-01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0'''