如何计算每个垃圾箱中的点数?

时间:2019-08-08 22:08:20

标签: python pandas numpy matplotlib binning

我有一个x,y坐标的熊猫df,想知道如何计算每个箱中的点数。我知道您可以使用plt.hist2d()进行可视化,但是我想制作某种数组/矩阵来保存每个bin的计数。

我使用以下方法对x,y坐标进行了装箱: bins = (df // .1 * .1).round(1).stack().groupby(level=0).apply(tuple) df在哪里:

     x         y
-2.319059 -4.057801
1.514416 -2.325972
-2.642251 -1.004367
-1.486476 -2.535654
-0.844162 -3.078726
-2.376592 -1.471239
-3.139233  0.449457
:
etc

bins是:

0       (-2.4, -4.1)
1        (1.5, -2.4)
3       (-2.7, -1.1)
4       (-1.5, -2.6)
6       (-0.9, -3.1)
7       (-2.4, -1.5)
8        (-3.2, 0.4)
:
etc

我尝试使用以下方法创建一个空的numpy数组:

x_size = int(max(list(df['x'])))
y_size = int(max(list(df['y'])))
my_array = np.zeros((x_size+1,y_size+1), np.int16)

但我不确定我如何将bin坐标与数组坐标关联以便对其进行计数。

1 个答案:

答案 0 :(得分:2)

只需groupby您的垃圾箱并使用GroupBy.count方法

bins.groupby(bins).count()