Pandas – count frequencies in bin intervals

You seem to mess up dir_interval and vel_interval. That said, I think you are looking for crosstab along with cut:

pd.crosstab(pd.cut(df['DIR'], vel_interval),
           pd.cut(df['VEL'], dir_interval))

Output:

VEL         (1, 2]  (2, 3]  (3, 4]  (4, 5]
DIR                                       
(0, 60]          1       2       1       0
(60, 120]        1       0       1       1
(120, 180]       0       1       1       0

Update: np.histogram2d is a good option but a bit more verbose:

hist, _, _ = np.histogram2d(x=df['DIR'], y=df['VEL'],
                             bins = (vel_interval, dir_interval))

out = pd.DataFrame(hist.astype(int), 
                   index=[f'{x}-{y}' for x,y in zip(vel_interval[:-1], 
                                                      vel_interval[1:])],
                   columns=[f'{x}-{y}' for x,y in zip(dir_interval[:-1], 
                                                    dir_interval[1:])]
                  )

Output:

         0-1  1-2  2-3  3-4  4-5
0-60       0    1    2    1    0
60-120     0    1    0    1    1
120-180    0    0    1    1    0
180-240    0    0    0    0    0
240-300    0    0    0    0    0
300-360    0    0    0    0    0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top