首页 > 解决方案 > 熊猫如何在没有分类值范围的情况下进行 bin 和 groupby

问题描述

我有大量的纬度和经度值,我想将它们组合在一起以便在热图中显示它们(在热图中ipyleaflet似乎只允许 2000 个左右的点,这在使用大数据时也会更有效率) .

我实际上正在使用vaex,但就其而言的答案pandas也很好。

pandas pd.cut函数在分箱方面似乎很有帮助,但是它会生成一个分类列 ( category dtype),它看起来像是分箱中所有值的列表。是否有某种方法可以将其更改为标识每个垃圾箱的增量数字(感谢 jezreal 的那部分答案)?我只需要一个 bin 编号,然后在纬度和经度列上groupby的 bin 编号和平均值 ( )。mean我还需要计算热图条目的强度。

例如:

dft = pd.DataFrame({
    'latitude': [1.5, 0.5, 1.2, 0.9, 3],
    'longitude': [3, 0.2, 2, 0.2, 1.1]
    })

dft['bin'] = pd.cut(dft['latitude'], bins=3, labels=False).astype(str) + "_" + pd.cut(dft['longitude'], bins=3, labels=False).astype(str)

dft.groupby('bin').agg(['mean', 'count']).unstack()

Almost gives me the answer, but I think I want this output instead:

bin latitude_mean longitude_mean count
0_0 0.7           0.2            2
0_1 1.2           2.0            1
1_2 1.5           3.0            1
2_0 3.0           1.1            1 

如果计数可以在 1 到 1000 之间标准化,将会很有帮助。

我如何使用行pandas pd.cut中的 bin 或其他东西groupby,平均纬度和经度以及列中的(热图强度)计数?

标签: python-3.xpandaspandas-groupbyvaex

解决方案


pandas pd.cut 函数在分箱方面似乎很有帮助,但是它会生成一个分类列(category dtype),它看起来像 bin 中所有值的列表。有没有办法把它改成一个递增的数字来识别每个垃圾箱

是的,使用label=False参数cut

标签数组或假,默认无
指定返回箱的标签。必须与生成的 bin 长度相同。如果为 False,则仅返回 bin 的整数指示符。

最后一次GroupBy.agg用于聚合和最后一次标准化count列:

df = dft.groupby('bin').agg(latitude_mean=('latitude','mean'),
                            longitude_mean=('longitude','mean'),
                            count=('latitude','count'))

#https://stackoverflow.com/a/50028155/2901002
a, b = 1, 1000
x, y = df['count'].min(),df['count'].max()
df['count'] = (df['count'] - x) / (y - x) * (b - a) + a

print (df)

     latitude_mean  longitude_mean   count
bin                                       
0_0            0.7             0.2  1000.0
0_1            1.2             2.0     1.0
1_2            1.5             3.0     1.0
2_0            3.0             1.1     1.0

推荐阅读