我有一个表,其中的行是用户对在线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:

  1. 硬编码属性列表(即属于属性的列名)
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']
  1. 使用itertools中的combinations创建不重复的所有唯一属性对的列表
from itertools import combinations
dim_pairs = list(combinations(dim, 2))
  1. 运行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

因此,我有一个数据帧字典,其中包含填充单个所需输出表所需的所有值,但不确定如何填充.或者不确定是否有更简单的方法.

推荐答案

您可以try 首先使用meltreshape df1,然后将corr与自定义函数一起使用:

tmp = (df1
   .melt(df1.columns.difference(dim))
   .assign(variable=lambda d: d['variable']+' '+d['value'].astype(str))
   .pivot(index='visit_id', columns='variable', values='items_bought')
)

def f(a, b):
    m = a == b
    return a[m].mean()

out = tmp.corr(f)

输出:

variable          age old  age young  is_US False  is_US True  is_website False  is_website True
variable                                                                                        
age old               1.0        NaN          3.0         0.0               NaN              1.5
age young             NaN        1.0          2.0         0.0               2.0              0.0
is_US False           3.0        2.0          1.0         NaN               2.0              3.0
is_US True            0.0        0.0          NaN         1.0               NaN              0.0
is_website False      NaN        2.0          2.0         NaN               1.0              NaN
is_website True       1.5        0.0          3.0         0.0               NaN              1.0

中级tmp:

variable  age old  age young  is_US False  is_US True  is_website False  is_website True
visit_id                                                                                
aa            NaN        0.0          NaN         0.0               NaN              0.0
ab            NaN        2.0          2.0         NaN               2.0              NaN
ac            0.0        NaN          NaN         0.0               NaN              0.0
ad            3.0        NaN          3.0         NaN               NaN              3.0

Python相关问答推荐

Django关于UniqueBindition的更新

如何在Pygame中绘制右对齐的文本?

我可以使用极点优化这个面向cpu的pandas代码吗?

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

如何将带有逗号分隔的数字的字符串解析为int Array?

由于瓶颈,Python代码执行太慢-寻求性能优化

数字梯度的意外值

添加包含中具有任何值的其他列的计数的列

如何计算列表列行之间的公共元素

点到面的Y距离

Django mysql图标不适用于小 case

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

Pandas 都是(),但有一个门槛

如果值不存在,列表理解返回列表

如何获取TFIDF Transformer中的值?

在Python中管理打开对话框

如何从pandas的rame类继承并使用filepath实例化

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

python—telegraph—bot send_voice发送空文件

如何找出Pandas 图中的连续空值(NaN)?