python-3.x - 熊猫如何在没有分类值范围的情况下进行 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
,平均纬度和经度以及列中的(热图强度)计数?
解决方案
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
推荐阅读
- google-apps-script - 根据表单条目将文件从 Google 表单多次上传到特定文件夹
- swift - Core Image 透视校正后 Swift Vision 的矩形检测失败
- openedge - 在 PROGRESS 4GL 中使用 SQL 减号操作?
- delphi - 使用 Delphi XE7 和 MyDac 在运行时创建 MySQL 表的问题
- .htaccess - 如何从 php codeigniter 中的 URL 隐藏 ID 和控制器?
- python - 从python Beautifulsoup中的span标签获取内容
- string - 带有十六进制代码的字符串与 Charset TComPort 的问题
- html - 在闪亮仪表板的动态框标题中转义 HTML
- python - 使用 np.where 和 np.select 的条件语句
- docker - Docker kill 命令不起作用:无法杀死容器