pivot_table set column as hour and index as date for a new dataframe

Question:

I need to get a new dataframe from a massive dataset so I am using pivot_table:

date is like 2020-12-31 09:00:00

And I need to show something like this:

import pandas as pd
import datetime as dt

pd.pivot_table(df_fuel, index=["date"].dt.date, columns=["date"].dt.hour, values=["Fuel_price"])

Once I run I get the following:

AttributeError: ‘list’ object has no attribute ‘dt’

I checked up the type of the objects and:

"Date" is datetime64[ns]
"Fuel_price" is float64

If I run without dt.date neither dt.hour just using the index "date" without columns it works:

pd.pivot_table(df_fuel, index=["date"], values=["Fuel_price"])

So, I don’t understand where is the mistake.

Asked By: Maria

||

Answers:

Better try:

pd.pivot_table(df_fuel, index=df_fuel["date"].dt.date,
               columns=df_fuel["date"].dt.hour, values =["Fuel_price"]

Inside every element of the pivot table, you have to indicate what data frame are you aiming for when you are just taking the date/hour.

Answered By: Uri