【问题标题】:Create grouped by percentages in SQL, converting from pandas在 SQL 中创建按百分比分组,从 pandas 转换
【发布时间】:2021-11-13 14:00:41
【问题描述】:

我想知道如何使用 SQL 计算特定数据结构的计数和百分比,已经使用 pandas 完成了。

给出以下示例数据:

groups_1 = ["group_1", "group_2", "group_3"]
groups_2 = ["type_1", "type_2", "type_3", "type_4"]
N = len(groups_1) * 40
np.random.seed(1)
example_data = pd.DataFrame(
    {
        "col_1": np.repeat(a=groups_1, repeats=N / len(groups_1)),
        "col_2": np.random.choice(a=groups_2, size=N),
    }
)

它的一个样本:

       col_1   col_2
97   group_3  type_2
117  group_3  type_3
59   group_2  type_1
35   group_1  type_2
26   group_1  type_3
41   group_2  type_2
28   group_1  type_2
78   group_2  type_2
4    group_1  type_4
18   group_1  type_3
1    group_1  type_4
34   group_1  type_2
46   group_2  type_3
11   group_1  type_2
64   group_2  type_2

我可以使用 python 和 pandas 创建计数和百分比,如下所示:

dt1 = (
    example_data.groupby(["col_1", "col_2"])
    .size()
    .rename("count", axis=0)
    .reset_index()
    .sort_values(by=["col_1", "col_2"])
)
dt1.join(
    dt1.groupby("col_1")["count"]
    .apply(lambda x: x.div(x.sum()).mul(100).round(1))
    .rename("percentage")
)

给出:

      col_1   col_2  count  percentage
0   group_1  type_1     12        30.0
1   group_1  type_2     10        25.0
2   group_1  type_3      9        22.5
3   group_1  type_4      9        22.5
4   group_2  type_1     10        25.0
5   group_2  type_2     15        37.5
6   group_2  type_3      6        15.0
7   group_2  type_4      9        22.5
8   group_3  type_1      8        20.0
9   group_3  type_2      7        17.5
10  group_3  type_3     10        25.0
11  group_3  type_4     15        37.5

这将如何在 SQL 而不是 pandas 中完成?

【问题讨论】:

    标签: python sql pandas group-by


    【解决方案1】:

    借助常用的表表达式和窗口函数,可以将您在 pandas 中使用的相同逻辑转换为 SQL。这是我在 SQL 中解决这个问题的方法

    WITH cte AS
    (
        SELECT 
            col_1, col_2, COUNT(*) AS cnt
        FROM 
            example_data
        GROUP BY
            col_1, col_2
    )
    SELECT
        *,
        ROUND(cnt * 100 / SUM(cnt) OVER (PARTITION BY col_1), 1) AS percentage
    FROM
        cte
    ORDER BY
        col_1, col_2
    

    结果

      col_1  col_2    cnt  percentage
    group_1 type_1     12        30.0
    group_1 type_2     10        25.0
    group_1 type_3      9        22.5
    group_1 type_4      9        22.5
    group_2 type_1     10        25.0
    group_2 type_2     15        37.5
    group_2 type_3      6        15.0
    group_2 type_4      9        22.5
    group_3 type_1      8        20.0
    group_3 type_2      7        17.5
    group_3 type_3     10        25.0
    group_3 type_4     15        37.5
    

    【讨论】:

    • @baxx 这回答了你的问题吗?
    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2019-04-11
    相关资源
    最近更新 更多