我正在处理数据集
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()
但我不确定如何汇总这些信息。
只需先将
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")