Pandas Dataframe - 在多列上装箱并获取另一列的统计信息

Fre*_*d S 10 python numpy binning pandas

问题

我有一个目标变量x和一些额外的变量AB. 我想计算满足和x某些条件时的平均值(和其他统计数据)。一个真实世界的例子是当太阳辐射 ( ) 和风速 ( ) 落入某些预定义的区间范围时,从一系列测量中计算平均气温 ( ) 。ABxAB

潜在的解决方案

我已经能够用循环来完成这个(见下面的例子),但我知道我应该避免在数据帧上循环。从我对这个网站的研究来看,我觉得使用pd.cut或可能有一个更优雅/矢量化的解决方案np.select,但坦率地说,我无法弄清楚如何去做。

例子

生成样本数据

import pandas as pd
import numpy as np

n = 100
df = pd.DataFrame(
    {
        "x": np.random.randn(n),
        "A": np.random.randn(n)+5,
        "B": np.random.randn(n)+10
    }
)
Run Code Online (Sandbox Code Playgroud)

df.head() 输出:

    x           A           B
0   -0.585313   6.038620    9.909762
1   0.412323    3.991826    8.836848
2   0.211713    5.019520    9.667349
3   0.710699    5.353677    9.757903
4   0.681418    4.452754    10.647738
Run Code Online (Sandbox Code Playgroud)

计算 bin 平均值

# define bin ranges
bins_A = np.arange(3, 8)
bins_B = np.arange(8, 13)

# prepare output lists
A_mins= []
A_maxs= []
B_mins= []
B_maxs= []
x_means= []
x_stds= []
x_counts= []

# loop over bins
for i_A in range(0, len(bins_A)-1):
    A_min = bins_A[i_A]
    A_max = bins_A[i_A+1]
    for i_B in range(0, len(bins_B)-1):
        B_min = bins_B[i_B]
        B_max = bins_B[i_B+1]
        
        # binning conditions for current step
        conditions = np.logical_and.reduce(
            [
                df["A"] > A_min,
                df["A"] < A_max,
                df["B"] > B_min,
                df["B"] < B_max,
            ]
        )
        
        # calculate statistics for x and store values in lists
        x_values = df.loc[conditions, "x"]
        x_means.append(x_values.mean())
        x_stds.append(x_values.std())
        x_counts.append(x_values.count())

        A_mins.append(A_min)
        A_maxs.append(A_max)
        B_mins.append(B_min)
        B_maxs.append(B_max)
        
Run Code Online (Sandbox Code Playgroud)

将结果存储在新的数据框中

binned = pd.DataFrame(
    data={
        "A_min": A_mins,
        "A_max": A_maxs,
        "B_min": B_mins,
        "B_max": B_maxs,
        "x_mean": x_means,
        "x_std": x_stds,
        "x_count": x_counts 
        }
)
Run Code Online (Sandbox Code Playgroud)

binned.head() 输出:

    A_min   A_max   B_min   B_max   x_mean      x_std       x_count
0   3       4       8       9       0.971624    0.790972    2
1   3       4       9       10      0.302795    0.380102    3
2   3       4       10      11      0.447398    1.787659    5
3   3       4       11      12      0.462149    1.195844    2
4   4       5       8       9       0.379431    0.983965    4
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 8

方法#1:Pandas + NumPy(有些到没有)

我们将尝试将其保留为 pandas/NumPy,以便我们可以利用数据帧方法或数组方法和 ufunc,同时在它们的级别对其进行矢量化。这使得在要解决复杂问题或要生成统计数据时更容易扩展功能,就像这里的情况一样。

现在,同时保持接近大熊猫解决这一问题,将产生类似于的组合的跟踪中间标识或标签A,并B在给定区间bins_Abins_B分别。为此,一种方法是分别使用searchsorted这两个数据 -

tagsA = np.searchsorted(bins_A,df.A)
tagsB = np.searchsorted(bins_B,df.B)
Run Code Online (Sandbox Code Playgroud)

现在,我们只对范围内的情况感兴趣,因此需要屏蔽 -

vm = (tagsB>0) & (tagsB<len(bins_B)) & (tagsA>0) & (tagsA<len(bins_A))
Run Code Online (Sandbox Code Playgroud)

让我们在原始数据帧上应用这个掩码 -

dfm = df.iloc[vm]
Run Code Online (Sandbox Code Playgroud)

添加有效标签的标签,这些标签将代表A_minsB_min等价物,因此将显示在最终输出中 -

dfm['TA'] = bins_A[(tagsA-1)[vm]]
dfm['TB'] = bins_B[(tagsB-1)[vm]]
Run Code Online (Sandbox Code Playgroud)

因此,我们的标记数据框已准备就绪,然后可以describe-d在对这两个标记进行分组后获取通用统计信息 -

df_out = dfm.groupby(['TA','TB'])['x'].describe()
Run Code Online (Sandbox Code Playgroud)

示例运行使事情更清楚,同时与有问题的已发布解决方案进行比较-

In [46]: np.random.seed(0)
    ...: n = 100
    ...: df = pd.DataFrame(
    ...:     {
    ...:         "x": np.random.randn(n),
    ...:         "A": np.random.randn(n)+5,
    ...:         "B": np.random.randn(n)+10
    ...:     }
    ...: )

In [47]: binned
Out[47]: 
    A_min  A_max  B_min  B_max    x_mean     x_std  x_count
0       3      4      8      9  0.400199  0.719007        5
1       3      4      9     10 -0.268252  0.914784        6
2       3      4     10     11  0.458746  1.499419        5
3       3      4     11     12  0.939782  0.055092        2
4       4      5      8      9  0.238318  1.173704        5
5       4      5      9     10 -0.263020  0.815974        8
6       4      5     10     11 -0.449831  0.682148       12
7       4      5     11     12 -0.273111  1.385483        2
8       5      6      8      9 -0.438074       NaN        1
9       5      6      9     10 -0.009721  1.401260       16
10      5      6     10     11  0.467934  1.221720       11
11      5      6     11     12  0.729922  0.789260        3
12      6      7      8      9 -0.977278       NaN        1
13      6      7      9     10  0.211842  0.825401        7
14      6      7     10     11 -0.097307  0.427639        5
15      6      7     11     12  0.915971  0.195841        2

In [48]: df_out
Out[48]: 
       count      mean       std  ...       50%       75%       max
TA TB                             ...                              
3  8     5.0  0.400199  0.719007  ...  0.302472  0.976639  1.178780
   9     6.0 -0.268252  0.914784  ... -0.001510  0.401796  0.653619
   10    5.0  0.458746  1.499419  ...  0.462782  1.867558  1.895889
   11    2.0  0.939782  0.055092  ...  0.939782  0.959260  0.978738
4  8     5.0  0.238318  1.173704  ... -0.212740  0.154947  2.269755
   9     8.0 -0.263020  0.815974  ... -0.365103  0.449313  0.950088
   10   12.0 -0.449831  0.682148  ... -0.436773 -0.009697  0.761038
   11    2.0 -0.273111  1.385483  ... -0.273111  0.216731  0.706573
5  8     1.0 -0.438074       NaN  ... -0.438074 -0.438074 -0.438074
   9    16.0 -0.009721  1.401260  ...  0.345020  1.284173  1.950775
   10   11.0  0.467934  1.221720  ...  0.156349  1.471263  2.240893
   11    3.0  0.729922  0.789260  ...  1.139401  1.184846  1.230291
6  8     1.0 -0.977278       NaN  ... -0.977278 -0.977278 -0.977278
   9     7.0  0.211842  0.825401  ...  0.121675  0.398750  1.764052
   10    5.0 -0.097307  0.427639  ... -0.103219  0.144044  0.401989
   11    2.0  0.915971  0.195841  ...  0.915971  0.985211  1.054452
Run Code Online (Sandbox Code Playgroud)

所以,正如前面提到的,我们有我们的A_minandB_minTAand TB,而相关的统计信息在其他标题中捕获。请注意,这将是一个多索引数据帧。如果我们需要捕获等效的数组数据,只需执行 :df_out.loc[:,['count','mean','std']].values对于 stats,而np.vstack(df_out.loc[:,['count','mean','std']].index)对于 bin interval-starts。

或者,要捕获不带 的等效统计数据describe,但使用数据帧方法,我们可以执行以下操作 -

dfmg = dfm.groupby(['TA','TB'])['x']
dfmg.size().unstack().values
dfmg.std().unstack().values
dfmg.mean().unstack().values
Run Code Online (Sandbox Code Playgroud)

替代方案#1:使用 pd.cut

我们也可以使用pd.cut问题中的建议来替换searchsorted更紧凑的,因为越界是自动处理的,保持基本思想不变 -

df['TA'] = pd.cut(df['A'],bins=bins_A, labels=range(len(bins_A)-1))
df['TB'] = pd.cut(df['B'],bins=bins_B, labels=range(len(bins_B)-1))
df_out = df.groupby(['TA','TB'])['x'].describe()
Run Code Online (Sandbox Code Playgroud)

所以,这给了我们统计数据。对于A_minB_min等价物,只需使用索引级别 -

A_min = bins_A[df_out.index.get_level_values(0)]
B_min = bins_B[df_out.index.get_level_values(1)]
Run Code Online (Sandbox Code Playgroud)

或者使用一些网格方法 -

mA,mB = np.meshgrid(bins_A[:-1],bins_B[:-1])
A_min,B_min = mA.ravel('F'),mB.ravel('F')
Run Code Online (Sandbox Code Playgroud)

方法#2:使用 bincount

我们可以np.bincount再次以矢量化方式利用获得所有这三个统计指标值,包括标准偏差 -

lA,lB = len(bins_A),len(bins_B)
n = lA+1

x,A,B = df.x.values,df.A.values,df.B.values

tagsA = np.searchsorted(bins_A,A)
tagsB = np.searchsorted(bins_B,B)

t = tagsB*n + tagsA

L = n*lB

countT = np.bincount(t, minlength=L)
countT_x = np.bincount(t,x, minlength=L)
avg_all = countT_x/countT
count = countT.reshape(-1,n)[1:,1:-1].ravel('F')
avg = avg_all.reshape(-1,n)[1:,1:-1].ravel('F')

# Using numpy std definition for ddof case
ddof = 1.0 # default one for pandas std
grp_diffs = (x-avg_all[t])**2
std_all = np.sqrt(np.bincount(t,grp_diffs, minlength=L)/(countT-ddof))
stds = std_all.reshape(-1,n)[1:,1:-1].ravel('F')
Run Code Online (Sandbox Code Playgroud)

方法#3:sorting利用reduceat方法-

x,A,B = df.x.values,df.A.values,df.B.values
vm = (A>bins_A[0]) & (A<bins_A[-1]) & (B>bins_B[0]) & (B<bins_B[-1])

xm = x[vm]

tagsA = np.searchsorted(bins_A,A)
tagsB = np.searchsorted(bins_B,B)

tagsAB = tagsB*(tagsA.max()+1) + tagsA
tagsABm = tagsAB[vm]
sidx = tagsABm.argsort()
tagsAB_s = tagsABm[sidx]
xms = xm[sidx]

cut_idx = np.flatnonzero(np.r_[True,tagsAB_s[:-1]!=tagsAB_s[1:],True])
N = (len(bins_A)-1)*(len(bins_B)-1)

count = np.diff(cut_idx)
avg = np.add.reduceat(xms,cut_idx[:-1])/count
stds = np.empty(N)
for ii,(s0,s1) in enumerate(zip(cut_idx[:-1],cut_idx[1:])):
    stds[ii] = np.std(xms[s0:s1], ddof=1)
Run Code Online (Sandbox Code Playgroud)

要获得与 Pandas 数据框样式输出相同或相似的格式,我们需要重塑。因此,它会是avg.reshape(-1,len(bins_A)-1).T等等。


vil*_*oro 5

如果您关心的是性能,则可以使用 for 循环,如果您使用numba,只需稍作更改

\n\n

这里有一个执行计算的函数。关键是它calculate使用 numba,所以速度非常快。其余的仅用于创建 pandas 数据框:

\n\n
from numba import njit\n\ndef calc_numba(df, bins_A, bins_B):\n    """ wrapper for the timeit. It only creates a dataframe """\n\n    @njit\n    def calculate(A, B, x, bins_A, bins_B):\n\n        size = (len(bins_A) - 1)*(len(bins_B) - 1)\n        out = np.empty((size, 7))\n\n        index = 0\n        for i_A, A_min in enumerate(bins_A[:-1]):\n            A_max = bins_A[i_A + 1]\n\n            for i_B, B_min in enumerate(bins_B[:-1]):\n                B_max = bins_B[i_B + 1]\n\n                mfilter = (A_min < A)*(A < A_max)*(B_min < B)*(B < B_max)\n                x_values = x[mfilter]\n\n                out[index, :] = [\n                    A_min,\n                    A_max,\n                    B_min,\n                    B_max,\n                    x_values.mean(),\n                    x_values.std(),\n                    len(x_values)\n                ]\n\n                index += 1\n\n        return out\n\n    columns = ["A_min", "A_max", "B_min", "B_max", "mean", "std", "count"]\n    out = calculate(df["A"].values, df["B"].values, df["x"].values, bins_A, bins_B)\n    return pd.DataFrame(out, columns=columns)\n
Run Code Online (Sandbox Code Playgroud)\n\n

性能测试

\n\n

使用n = 1_000_000和 相同bins_Abins_B我们得到:

\n\n
%timeit code_question(df, bins_A, bins_B)\n15.7 s \xc2\xb1 428 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 1 loop each)\n\n%timeit calc_numba(df, bins_A, bins_B)\n507 ms \xc2\xb1 12.3 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 1 loop each)\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

它比问题中的代码快大约30

\n
\n\n

由于内置方法使用类似的增强功能,因此很难击败 numba 性能pandas

\n