【问题标题】:De-aggregate data in PandasPandas 中的数据去聚合
【发布时间】:2022-01-13 04:25:53
【问题描述】:

我正在尝试弄清楚如何使用 pandas/matplotlib 中的预聚合数据。 我正在从 Kibana/ElasticSearch 中提取我的数据,所以它不是原始数据,它已经被聚合到存储桶中。

一些示例数据看起来像这样(实际数据有更多的类别和高达 40 个的桶)。

Category,Bucket,Count
A,0,134563
B,0,215777
C,0,149918
A,1,183394
B,1,430333
C,1,234846
A,2,301137
B,2,604825
C,2,369665
A,3,385299
B,3,638058
C,3,471866

我意识到,由于数据已经聚合,我不能使用任何分布图,但我可以将上述数据绘制在通用条形图中以查看分布。这行得通。

我现在要做的是从describe() 中提取平均值/中位数(每个类别)等统计数据和其他统计数据,并将它们绘制在箱线图上。

如何“去聚合”我的数据或以其他方式将其转换回原始数据,以便更自然地使用它?

我从 Pandas get median/average of pre-aggregated data 那里得到了关于使用 np.repeat() 将我的计数扩展到原始数据的提示。我的计数太高了,但我认为我可以除以 10 或 100 以获得合理的近似值。

所以我想我明白我想做什么,我就是不能让 np/pandas 完成它。

np.repeat(df['Bucket'], df['Count'] / 10).describe()

count    411961.000000
mean          1.914108
std           1.023361
min           0.000000
25%           1.000000
50%           2.000000
75%           3.000000
max           3.000000

# Think that's working?  But now how do I break it down by Category?
byCat = df.groupby('Category')
np.repeat(byCat['Bucket'], byCat['Count'] / 10).describe()

TypeError: unsupported operand type(s) for /: 'SeriesGroupBy' and 'int'

【问题讨论】:

标签: python pandas numpy matplotlib


【解决方案1】:

您可以按类别分组,然后计算每个类别的统计信息:

import pandas as pd
import numpy as np

for cat, df_cat in df.groupby('Category'):
    print(f'\nCategory: {cat}')
    print(np.repeat(df_cat['Bucket'], df_cat['Count'] / 10).describe())

输出:

Category: A
count    100437.000000
mean          1.933072
std           1.047681
min           0.000000
25%           1.000000
50%           2.000000
75%           3.000000
max           3.000000
Name: Bucket, dtype: float64

Category: B
count    188897.000000
mean          1.881512
std           1.004221
min           0.000000
25%           1.000000
50%           2.000000
75%           3.000000
max           3.000000
Name: Bucket, dtype: float64

Category: C
count    122627.000000
mean          1.948788
std           1.030864
min           0.000000
25%           1.000000
50%           2.000000
75%           3.000000
max           3.000000
Name: Bucket, dtype: float64

【讨论】:

    猜你喜欢
    • 2012-08-26
    • 1970-01-01
    • 2016-07-13
    • 2017-02-05
    • 2017-06-07
    • 2017-01-27
    • 2019-05-20
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多