python - Pandas:如何找到列的分箱均值

标签 python python-3.x pandas numpy dataframe

我们如何有效地找到 pandas 数据框中列的分箱均值?

我喜欢将列分成 5 个部分,然后求出每个部分的平均值。

这是我做的:

import numpy as np
import pandas as pd

df = pd.DataFrame({'x': np.arange(20)})
n_bins = 5
dfs = np.array_split(df,n_bins)

x_means = [x.mean()[0] for x in dfs]
n_elems = len(df) // n_bins
x_mean_lst = [[i]*n_elems for i in x_means]
x_mean_array = np.array(x_mean_lst).flatten()
df['x_bin_mean'] = x_mean_array
df

这似乎比必要的更复杂。有没有更好的选择?

输出应该是这样的:

     x  x_bin_mean
0    0         1.5
1    1         1.5
2    2         1.5
3    3         1.5
4    4         5.5
5    5         5.5
6    6         5.5
7    7         5.5
8    8         9.5
9    9         9.5
10  10         9.5
11  11         9.5
12  12        13.5
13  13        13.5
14  14        13.5
15  15        13.5
16  16        17.5
17  17        17.5
18  18        17.5
19  19        17.5

最佳答案

我猜你想要类似的东西

df.groupby(df.index // (len(df) // n_bins))['x'].transform('mean')

或者,如果您的索引不是数字,

df.groupby(pd.RangeIndex(len(df)) // (len(df) // n_bins))['x'].transform('mean')

这是 n_bins = 5 的石斑鱼和输出的样子,

df.index // (len(df) // 5)
# Int64Index([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4], dtype='int64')

df['x_bin_mean'] = (
    df.groupby(df.index // (len(df) // 5))['x'].transform('mean'))
df.head(10)

   x  x_bin_mean
0  0         1.5
1  1         1.5
2  2         1.5
3  3         1.5
4  4         5.5
5  5         5.5
6  6         5.5
7  7         5.5
8  8         9.5
9  9         9.5

请注意,整数除法虽然速度很快,但可能无法处理索引不均分的情况:

I'm not sure that the integer division is fully correct (if things don't divide evenly). For instance with a length of 16 and n_bins=5 you get 6 groups —Alollz

在这种情况下,使用 Alollz 对 pd.qcut 的有用建议:

df.groupby(pd.qcut(df.index, n_bins))['x'].transform('mean')

关于python - Pandas:如何找到列的分箱均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56761120/

相关文章:

python - Python 3 中带选项的 Curl 命令

python - YouTube-dl API : 'h' is not a valid URL

python - 从 Python 控制 "daemon-like"linux 脚本

python-3.x - 为 CLI 脚本构建 python 包

python - PyDAQmx.Task() 引发 RecursionError

python - 在 groupby 对象中用 "ones"填充缺失的组合

python - 使用 interp1d 在数据帧中按行插值

python : ValueError: invalid literal for int() with base 10: ' '

python - 如何在Python中下载文件时制作进度条

python - 合并列的重复单元格