使用scipy.stats.binned_statistic_2d计算2D数据的多个统计数字

问题描述 投票:1回答:1

我有关于scipy.stats.binned_statistic_2d函数的问题,如下:

我有2-D数据(x,y,f(x,y)),我想将x-y平面分区并计算每个bin的一些统计数据。为此,我使用非常方便的函数sbinned_statistic_2d。但是我们假设我想计算每个箱子的几个统计值 - 让我们说平均值和中位数。因此我发现尝试这样的事情是很自然的

stats.binned_statistic_2d(data["x"], data["y"], data["f"], statistic = lambda x: [ np.mean(x), np.median(x) ], bins = bin_number )

但这不起作用,因为binned_statistic_2d期望统计函数只返回标量,而不是标量列表。

当然我可以两次调用binned_statistic_2d,但由于bin_number对我来说相当高,而且数据是一个庞大的数据帧,这需要很多时间。

那么,当我想用​​这个函数一次计算几个统计函数时,你有什么想法,我能做什么而不是多次执行binned_statistic_2d

为了玩,一个小的工作示例:

import pandas as pd
from scipy import stats

df = pd.DataFrame([  [i,j,i*j] for i in range(10) for j in range(10)], columns = ["x", "y", "f"])
# The following works
hist, _, _, _ = stats.binned_statistic_2d(df["x"], df["y"], df["f"], statistic = lambda x:  np.mean(x)  ,bins=4)    
# The following doesn't work
hist, _, _, _ = stats.binned_statistic_2d(df["x"], df["y"], df["f"], statistic = lambda x:  [ np.mean(x), np.median(x) ]  ,bins=4)

在此先感谢,Jürgen

python scipy statistics histogram binning
1个回答
1
投票

你想使用pandas.DataFrame.pivot_table。您可以使用aggfunc指定要聚合的多个函数。

© www.soinside.com 2019 - 2024. All rights reserved.