Search code examples
pythondatetimegroup-by

Group by date and another field


I think I am missing the obvious but I can't seem to group my data using the group by function. To clarify I have a station ID and the date with the other columns being status Id, bikes available and docks available. I want to group my data by the date and station ID with the bikes available and docks available calculated as the mean but it doesn't seem to work.

My code is as follows:

Final_Df=df.groupby([df['date'].dt.date],df['station_id']).mean()

The type error shows 'Series objects are not mutable, this they cannot be hashed.

I am new to python - any help?

Tried replacing df['station_id'] with just station_id but to no avail. Thanks in advance


Solution

  • Your groupby argument should be a single list [df['date'].dt.date ,df['station_id']] (note the closing bracket to the right of ['station_id'].

    df = pd.DataFrame({'Date_Time': pd.date_range('10/1/2001 10:00:00', periods=3, freq='10H'),
                       'B':[4,5,6],
                       'station_id':[1, 1, 2]})
                       
    df.groupby([df['Date_Time'].dt.date, df['station_id']]).mean()
    

    results in

                             B
    Date_Time  station_id     
    2001-10-01 1           4.5
    2001-10-02 2           6.0