使用两个具有“年”和“月”信息的独立系列构建热图

问题描述 投票:0回答:1

我正在处理数据集

d = {'date_added_month': ['February', 'December', 'October', 'December', 'April','December', 'March', 'April'], 
     'date_added_year': [2014, 2012, 2008, 2009, 2010, 2011, 2012, 2013],
    'title': ['apple', 'ball', 'cat', 'dog', 'elephant', 'fish', 'goat', 'horse'],
    'titles_count': [0,0,0,0,0,0,0,0]}
df = pd.DataFrame(data=d)

我想构建一个 X 轴为年份、Y 轴为月份的热图,并计算特定月份和年份的标题数量。如何计算月份和年份的标题数量?

我已经按月和年计算了标题,如下所示:

grp_by_yr = df.groupby("date_added_year").size()
grp_by_mn =  df.groupby("date_added_month").size()

但我不确定如何汇总这些信息。

pandas dataframe seaborn data-analysis
1个回答
2
投票

只需先将

titles_count
填入 1,因为它们表示每行 1 个计数。

release_dist_df['titles_count'] = 1

然后像这样旋转桌子 -

heatmap1_data = pd.pivot_table(release_dist_df, values='titles_count', 
                     index=['date_added_month'], 
                     columns='date_added_year')

然后使用seaborn绘图-

sns.heatmap(heatmap1_data, cmap="YlGnBu")

更新

按要求更新分组

import pandas as pd

d = {'date_added_month': ['February', 'February', 'December', 'October', 'December', 'April','December', 'March', 'April'],
     'date_added_year': [2014, 2014, 2012, 2008, 2009, 2010, 2011, 2012, 2013],
    'title': ['apple', 'apple-new', 'ball', 'cat', 'dog', 'elephant', 'fish', 'goat', 'horse'],
    'titles_count': [0,0,0,0,0,0,0,0,0]}
df = pd.DataFrame(data=d)
df['titles_count'] = 1

group_by_both = df.groupby(["date_added_year", "date_added_month"]).agg({'titles_count': 'sum'})

heatmap1_data = pd.pivot_table(group_by_both, values='titles_count',
                     index=['date_added_month'],
                     columns='date_added_year')
print(heatmap1_data)

import seaborn as sns
sns_plot = sns.heatmap(heatmap1_data, cmap="YlGnBu")

我还添加了一个数据点来表明聚合正在发挥作用(2014 年 2 月)。

© www.soinside.com 2019 - 2024. All rights reserved.