Python Pandas group datetimes by hour and count row

2024/11/16 4:11:10

This is my transaction dataframe, where each row mean a transaction :

date               station
30/10/2017 15:20    A
30/10/2017 15:45    A
31/10/2017 07:10    A
31/10/2017 07:25    B
31/10/2017 07:55    B

I need to group the start_date to a hour interval and count each city, so the end result will be:

date        hour      station   count
30/10/2017  16:00        A       2
31/10/2017  08:00        A       1
31/10/2017  08:00        B       2

Where the first row means from 15:00 to 16:00 on 30/10/2017, there are 2 transactions in station A

How to do this in Pandas?

I tried this code, but the result is wrong :

df_start_tmp = df_trip[['Start Date', 'Start Station']]times = pd.DatetimeIndex(df_start_tmp['Start Date'])df_start = df_start_tmp.groupby([times.hour, df_start_tmp['Start Station']]).count()

Thanks a lot for the help

Answer

IIUC size+pd.Grouper

df.date=pd.to_datetime(df.date)
df.groupby([pd.Grouper(key='date',freq='H'),df.station]).size().reset_index(name='count')
Out[235]: date station  count
0 2017-10-30 15:00:00       A      2
1 2017-10-31 07:00:00       A      1
2 2017-10-31 07:00:00       B      2
https://en.xdnf.cn/q/71711.html

Related Q&A

Get Bokehs selection in notebook

Id like to select some points on a plot (e.g. from box_select or lasso_select) and retrieve them in a Jupyter notebook for further data exploration. How can I do that?For instance, in the code below, …

Upload CSV file into Microsoft Azure storage account using python

I am trying to upload a .csv file into Microsoft Azure storage account using python. I have found C-sharp code to write a data to blob storage. But, I dont know C# language. I need to upload .csv file …

GeoDjango: How can I get the distance between two points?

My Profile model has this field:location = models.PointField(geography=True, dim=2, srid=4326)Id like to calculate the distance between the two of these locations (taking into account that the Earth is…

Reading direct access binary file format in Python

Background:A binary file is read on a Linux machine using the following Fortran code:parameter(nx=720, ny=360, nday=365) c dimension tmax(nx,ny,nday),nmax(nx,ny,nday)dimension tmin(nx,ny,nday),nmin(nx,…

Fabric/Python: AttributeError: NoneType object has no attribute partition

Have the following function in fabric for adding user accounts.~/scripts #fab -lPython source codeAvailable commands:OS_TYPEadduser_createcmd Create command line for adding useradduser_getinfo Prom…

Python object @property

Im trying to create a point class which defines a property called "coordinate". However, its not behaving like Id expect and I cant figure out why. class Point:def __init__(self, coord=None…

Tkinter - Inserting text into canvas windows

I have a Tkinter canvas populated with text and canvas windows, or widgets, created using the create_text and create_window methods. The widgets I place on the canvas are text widgets, and I want to in…

How to run nosetests without showing of my matplotlibs graph?

I try to run my test without any messages displaying from my main program. I only want verbose messages from nosetests to display.For example: nosetests -v --nologcaptureAll of my printout messages fro…

Variable name to string in Python

I have written some code in Python and I would like to save some of the variables into files having the name of the variable. The following code:variableName1 = 3.14 variableName2 = 1.09 save_variable_…

In Python, how to print FULL ISO 8601 timestamp, including current timezone

I need to print the FULL local date/time in ISO 8601 format, including the local timezone info, eg:2007-04-05T12:30:00.0000-02:00I can use datetime.isoformat() to print it, if I have the right tzinfo o…