在 SQL 中创建分类字典并在 Python 中聚合它们

Creating a dictionary of categoricals in SQL and aggregating them in Python

我有一个相当 "cross platformed" 的问题。希望不要太笼统。

我的 table 之一,比如 customers,包含我的客户 ID 及其相关的人口统计信息。另一个 table,比如 transaction,包含客户在各个商店的所有购买。 我有兴趣在 python 中分析篮子构成和人口统计数据。因此,我想将商店作为列,并将商店中给定客户的总和作为我的数据框

为清楚起见,

 select *
 from customer
 where id=1 or id=2

给我

 id     age      gender
 1      35       MALE
 2      57       FEMALE

 select *
 from transaction
 where id=1 or id=2

给我

 customer_id     shop     amount
 1               2        250
 1               2        500
 2               3        100
 2               7        200
 2               11       125

它应该在(最好)Pandas 数据帧中作为

 id     age      gender      shop_2     shop_3     shop_7   shop_11
 1      35       MALE        750        0          0        0   
 2      57       FEMALE      0          100        200      125

最后一列是客户的汇总篮子。

我尝试通过以下方式为 SQL 中的每个客户创建一个 python 购买和金额字典:

 select customer_id, array_agg(concat(cast(shop as varchar), ' : ', cast(amount as varchar))) as basket
 from transaction
 group by customer_id

导致

 id    basket
 1     ['2 : 250', '2 : 500']
 2     ['3 : 100', '7 : 200', '11 : 125']

可以轻松加入客户 table。

但是,这个解决方案并不是最优的,因为它是字符串而不是 [] 中的整数。因此,它涉及 python 中的大量操作和循环以使其成为我想要的格式。

有什么方法可以汇总 SQL 中的购买,让 python 更容易阅读和汇总到列中?

一个简单的解决方案是在 pandas 中使用 pivot_table on the second dataframe and then merge 进行聚合,第一个:

df2 = df2.pivot_table(columns='shop', values='amount', index='customer_id', aggfunc='sum', fill_value=0.0).reset_index()
df = pd.merge(df1, df2, left_on='id', right_on='customer_id')

结果数据帧:

id  age  gender   2   3   7  11
 1   35    MALE 750   0   0   0
 2   57  FEMALE   0 100 200 125