【发布时间】: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