来自两个类别百分比的Python热图

2024-05-15 01:14:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由两列组成的数据集,每列是一个类别,每行代表一个用户。用户在一列中有一个年龄范围,在另一列中有一个类别(A-E)

我想找出每个年龄段的用户在每个类别中的百分比。 例如:

18-25: A - 25%, B - 35%, C - 30%, D - 5%, E - 5%
26-40: A - 15%, B - 45%, C - 10%, D - 15%, E - 15%

有了这些信息,我想创建一种热图,其中年龄范围向下延伸 分类也排在最前面。每个细胞的“热度”就是相应类别/年龄范围的百分比有多高

任何帮助都将不胜感激

谢谢


Tags: 数据用户信息分类代表类别细胞百分比
1条回答
网友
1楼 · 发布于 2024-05-15 01:14:33

以下是我使用pandas、numpy和seaborn的解决方案:

import pandas as pd
import numpy as np
import seaborn
import matplotlib.pyplot as plt

# Create summaryTable
ageGroups = np.array(["18-25","26-40"])
categories = np.array(['A','B','C','D','E'])
summaryTable = pd.DataFrame(index=ageGroups, columns=categories)

ageGroupsInts = np.array([18,25,26,40])

counter = 0
for i in range(0, ageGroupsInts.shape[0], 2):
    inAgeGroupI = df.loc[df.Age >= ageGroupsInts[i]].loc[df.Age <= ageGroupsInts[i+1]]
    numEntries = inAgeGroupI.shape[0]
    
    for j in range(categories.shape[0]):
        df_catJ = inAgeGroupI.loc[inAgeGroupI.Category == categories[j]]
        
        summaryTable.at[ageGroups[counter], categories[j]] = df_catJ.shape[0] / numEntries * 100
        
    counter += 1
        

# Create heatmap 
summaryTable_np = summaryTable.to_numpy().astype(float)
xLabels = categories
yLabels = ageGroups
seaborn.heatmap(summaryTable_np, annot=True, linewidths=.5, square=True, 
                xticklabels=xLabels, yticklabels=yLabels,
                vmin=np.amin(summaryTable_np), vmax=np.amax(summaryTable_np), cmap='Reds')
plt.yticks(rotation=0) 

其中df是一个(nRows,2)大小的数据框,列为“年龄”和“类别”,而summaryTable是一个数据框,列为年龄组,行为a-E类别

下面是一个示例输出热图:
heatmap

相关问题 更多 >

    热门问题