【问题标题】:Python Heatmap from percentages of two categories来自两个类别百分比的 Python 热图
【发布时间】:2020-08-05 12:56:59
【问题描述】:

我有一个由两列组成的数据集,每一列是一个类别,每一行代表一个用户。用户将在一列中有一个年龄范围,在另一列中有一个类别 (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%

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

任何帮助将不胜感激

谢谢

【问题讨论】:

    标签: python pivot-table seaborn heatmap


    【解决方案1】:

    这是我使用 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 类别为列。

    这是一个示例输出热图:

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 2020-12-15
      • 2017-06-20
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多