我有一个表,其中的行是用户对在线store 的个人访问.有多个列是访问的属性(可以是布尔值,也可以是具有2个以上可能值的分类属性).还有一个栏目统计了在那次访问中购买了多少物品.
我想创建一个表,按每个属性对汇总每次访问购买的平均物品数量.即,对于给定的属性对值,将购买的物品数量相加,并除以该属性对的行数.然后,我会使用这张表将其可视化为热图.
This is similar to preparing separate heatmaps for every attribute-pair. But would want to do this in one table or heatmap for easier digestibility.个
Note than along the diagonal when the same attributes are being compared the result is always 1, or when mutually exclusive attributes are compared the result is NA. The cells left empty are the same as the ones filled in above the diagonal.个
输入表:
visit_id | age | is_website | is_US | items_bought |
---|---|---|---|---|
aa | young | true | true | 0 |
ab | young | false | false | 2 |
ac | old | true | true | 0 |
ad | old | true | false | 3 |
所需输出表:
age young | age old | is_website true | is_website false | is_US true | is_US false | |
---|---|---|---|---|---|---|
age young | 1 | NA | 0 | 2 | 0 | 2 |
age old | NA | 1 | 1.5 | null division | 0 | 3 |
is_website true | 1 | NA | 0 | 3 | ||
is_website false | NA | 1 | null division | 2 | ||
is_US true | 1 | NA | ||||
is_US false | NA | 1 |
What I tried:个
- 硬编码属性列表(即属于属性的列名)
data = {
'visit_id': ['aa', 'ab', 'ac', 'ad'],
'age': ['young', 'young', 'old', 'old'],
'is_website': [True, False, True, True],
'is_US': [True, False, True, False],
'items_bought': [0, 2, 0, 3]
}
import pandas as pd
df1 = pd.DataFrame(data)
dim = ['age', 'is_website', 'is_US']
- 使用
itertools
中的combinations
创建不重复的所有唯一属性对的列表
from itertools import combinations
dim_pairs = list(combinations(dim, 2))
- 运行for循环:
- 按属性对数据框进行分组,计算购买的商品总数(
total_items_bought
)并计算行数(total_visits
) - 向生成的数据帧
items_bought_per_visit
添加一个新列,即total_items_bought / total_visits
- 将生成的数据帧保存到词典
dfs = {}
for x in range(len(dim_pairs)):
grouped = df1.groupby([dim_pairs[x][0], dim_pairs[x][1]]).agg({'items_bought': 'sum', 'visit_id': 'count'}).reset_index()
grouped['items_bought_per_visit'] = grouped['items_bought'] / grouped['visit_id']
pivot_df = grouped.pivot_table(index=dim_pairs[x][0], columns=dim_pairs[x][1], values='items_bought_per_visit', aggfunc='sum').fillna(0)
df_name = f"pivot_df{x}"
dfs[df_name] = pivot_df
因此,我有一个数据帧字典,其中包含填充单个所需输出表所需的所有值,但不确定如何填充.或者不确定是否有更简单的方法.