【问题标题】:Python heat map from two categorical variable columns来自两个分类变量列的 Python 热图
【发布时间】:2020-11-25 13:31:23
【问题描述】:

您好,我需要从只有两列的数据框中绘制热图。 这些列由大约 300 行组成。每行都有一个用户指定的类别 (A-E),分数在 1-5 之间。

我想将每个类别的用户得分百分比显示为热图。

例如

    1  2   3   4  5
A  70% 10% 10% 5% 5%
B  50% 20% 10% 8% 2%
C  30% 40% 10% 10% 10%
D  10% 30% 20% 30% 10%
E  20% 20% 40% 15% 5%

提前致谢!

【问题讨论】:

    标签: python split heatmap categorical-data


    【解决方案1】:

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

    import numpy as np
    import pandas as pd
    import seaborn
    import matplotlib.pyplot as plt
    
    # Create summaryTable
    categories = np.array(['A','B','C','D','E'])
    summaryTable = pd.DataFrame(index=categories, columns=np.arange(1,6))
    
    for i in range(summaryTable.shape[0]):
        for j in range(summaryTable.shape[1]):
            df_ij = df.loc[df.Category == summaryTable.index[i]].loc[df.Score == summaryTable.columns[j]]
            numOccurances = df_ij.shape[0]
            numOccurancesCat = df.loc[df.Category == summaryTable.index[i]].shape[0]
            
            summaryTable.at[categories[i], j+1] = numOccurances / numOccurancesCat * 100
            
    # Create heatmap 
    summaryTable_np = summaryTable.to_numpy().astype(float)
    xLabels = np.arange(1,6)
    yLabels = categories
    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 是您的数据框,大约有 300 行和 2 列,summaryTable 是用户得分百分比表。

    这是一个示例热图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 2018-05-21
      相关资源
      最近更新 更多