【问题标题】:Querying data in pandas where points are grouped by a hexbin function在 pandas 中查询数据,其中点按 hexbin 函数分组
【发布时间】:2019-06-05 10:14:22
【问题描述】:

seaborn 和 pandas 都提供 API,以便将二元直方图绘制为 hexbin 图(下图示例)。但是,我正在搜索对位于同一 hexbin 中的点执行查询。是否有一个函数可以检索与 hexbin 中的数据点关联的行?

举个例子: 我的数据框包含 3 行:ABC。我使用sns.jointplot(x=A,y=B) 来绘制密度。现在,我想对位于同一 bin 中的每个数据点执行查询。例如,对于每个 bin,计算与每个点关联的 C 值的平均值。

【问题讨论】:

  • 您可以绘制均值。你是这个意思吗?当然,您也可以从绘图中检索数据。
  • @ImportanceOfBeingErnest,我对绘制值不感兴趣,而是将原始数据帧“转换”为数据帧,其中每一行代表一个十六进制,其中列包含基于对原始值进行的某些处理的值在那个 hexbin 中。
  • 我不知道任何可以在六边形网格上运行的辅助函数。 matplotlib hexbin source code 相当低级。当然可以复制它来实现类似的东西。

标签: python pandas numpy scipy seaborn


【解决方案1】:

当前解决方案——快速破解

目前,我已经实现了以下函数,以将函数应用于与位于同一 hexbin 中的 (x,y) 坐标关联的数据:

def hexagonify(x, y, values, func=None):

    hexagonized_list = []

    fig = plt.figure()
    fig.set_visible(False)
    if func is not None:
        image = plt.hexbin(x=x, y=y, C=values, reduce_C_function=func)
    else:
        image = plt.hexbin(x=x, y=y, C=values)

    values = image.get_array()

    verts = image.get_offsets()
    for offc in range(verts.shape[0]):
            binx, biny = verts[offc][0], verts[offc][1]
            val = values[offc]
            if val:
                hexagonized_list.append((binx, biny, val))

    fig.clear()
    plt.close(fig)
    return hexagonized_list

值(与 x 或 y 大小相同)通过 values 参数传递。 hexbin 是通过matplotlibhexbin 函数计算的。这些值是通过返回的PolyCollectionget_array() 函数检索的。默认情况下,np.mean 函数应用于每个 bin 的累积值。可以通过向func 参数提供函数来更改此功能。随后,get_offsets() 方法允许我们计算 bin 的中心 (discussed here)。通过这种方式,我们可以(默认情况下)关联每个 hexbin 提供的值的平均值。但是,此解决方案是一个 hack,因此欢迎对此解决方案进行任何改进。

【讨论】:

  • 是的,这就是我在另一个答案下方my comment 的意思。
【解决方案2】:

来自matplotlib

如果你已经画好了情节,你可以从polycollection得到由matplotlib返回的Bin Counts:

polycollection:一个 PolyCollection 实例;在此使用 PolyCollection.get_array 来获取每个六边形的计数。

此功能也可用于:

pandas

这里的 MCVE 只使用可以处理 C 属性的 pandas

import numpy as np
import pandas as pd

# Trial Dataset:
N=1000
d = np.array([np.random.randn(N), np.random.randn(N), np.random.rand(N)]).T
df = pd.DataFrame(d, columns=['x', 'y', 'c'])

# Create bins: 
df['xb'] = pd.cut(df.x, 3)
df['yb'] = pd.cut(df.y, 3)

# Group by and Aggregate:
p = df.groupby(['xb', 'yb']).agg('mean')['c']
p.unstack()

首先我们使用pandas.cut 创建垃圾箱。然后我们group by and aggregate。您可以选择您喜欢的agg 函数聚合C(例如maxmedian 等)。

输出大约是:

yb               (-2.857, -0.936]  (-0.936, 0.98]  (0.98, 2.895]
xb                                                              
(-2.867, -0.76]          0.454424        0.519920       0.507443
(-0.76, 1.34]            0.535930        0.484818       0.513158
(1.34, 3.441]            0.441094        0.493657       0.385987

【讨论】:

  • 当然,绘制一些东西然后删除绘图以只保留数据是一个丑陋但简单的选择。
  • @ImportanceOfBeingErnest,添加了快捷方式
  • 我如何能够从该多集合中获取关联的 C 列值?我知道只能从 hexbins 中提取计数,而不是特定 hexbins 中点的 x 和 y 值?
  • 此方法不使用 hexbins,而是使用矩形或在您的情况下为方形 bins。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 2019-09-20
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
相关资源
最近更新 更多