Eam*_*phy 5 python pivot-table dataframe pandas
我在以日期时间值作为索引来旋转数据框时遇到一些麻烦。我的 df 看起来像这样:
Timestamp Value
2016-01-01 00:00:00 16.546900
2016-01-01 01:00:00 16.402375
2016-01-01 02:00:00 16.324250
Run Code Online (Sandbox Code Playgroud)
其中时间戳是a,datetime64[ns]。我正在尝试旋转桌子,使其看起来像这样。
Hour 0 1 2 4 ....
Date
2016-01-01 16.5 16.4 16.3 17 ....
....
....
Run Code Online (Sandbox Code Playgroud)
我尝试使用下面的代码,但运行时出现错误。
df3 = pd.pivot_table(df2,index=np.unique(df2.index.date),columns=np.unique(df2.index.hour),values=df2.Temp)
Run Code Online (Sandbox Code Playgroud)
KeyError Traceback (most recent call last)
in ()
1 # Pivot Table
----> 2 df3 = pd.pivot_table(df2,index=np.unique(df2.index.date),columns=np.unique(df2.index.hour),values=df2.Temp)
~\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py in pivot_table(data, values, index, columns, aggfunc, fill_value, margins, dropna, margins_name)
56 for i in values:
57 if i not in data:
---> 58 raise KeyError(i)
59
60 to_filter = []
KeyError: 16.5469
Run Code Online (Sandbox Code Playgroud)
任何帮助或见解将不胜感激。
我稍微扩展了输入数据,如下所示(假设在同一日期/小时没有重复的条目)
Timestamp Value
2016-01-01 00:00:00 16.546900
2016-01-01 01:00:00 16.402375
2016-01-01 02:00:00 16.324250
2016-01-01 04:00:00 16.023928
2016-01-03 04:00:00 16.101919
2016-01-05 23:00:00 13.405928
Run Code Online (Sandbox Code Playgroud)
看起来有点尴尬,但像下面这样的东西是有效的。
df2['Date'] = df2.Timestamp.apply(lambda x: str(x).split(" ")[0])
df2['Hour'] = df2.Timestamp.apply(lambda x: str(x).split(" ")[1].split(":")[0])
df3 = pd.pivot_table(df2, values='Value', index='Date', columns='Hour')
Run Code Online (Sandbox Code Playgroud)
[输出]
Hour 00 01 02 04 23
Date
2016-01-01 16.5469 16.402375 16.32425 16.023928 NaN
2016-01-03 NaN NaN NaN 16.101919 NaN
2016-01-05 NaN NaN NaN NaN 13.405928
Run Code Online (Sandbox Code Playgroud)
最后,如果您的列需要是整数,
df3.columns = [int(x) for x in df3.columns]
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。