gpt4 book ai didi

python - 热图的正确顺序的数据透视表

转载 作者:行者123 更新时间:2023-12-05 05:53:06 24 4
gpt4 key购买 nike

在创建热图时,我有以下语法:

import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
data=df.rename(columns={0:'Year', 1:'Month', 2:'Count'})
data= pd.pivot_table(data, values='Count', index='Year', columns='Month')
f, ax = plt.subplots(figsize=(15, 6))
sns.heatmap(data, annot=True, fmt="d", linewidths=.5, ax=ax)

并生成以下热图:

enter image description here

我想要的是沿 x 轴的月份升序或降序。即一月、二月、三月等。我如何完成 this

示例数据在这里:

    0        1      2
0 2005 Jan 84482
1 2011 Apr 28243
2 2007 Apr 64992
3 2013 Feb 46542
4 2016 Sept 24445
5 2011 July 23346
6 2019 Dec 28251
7 2015 Jan 34505
8 2007 June 72561
9 2015 Apr 26973
10 2006 May 102896
11 2006 Jan 88664
12 2012 Nov 32046
13 2005 Sept 65498
14 2014 Sept 24856

最佳答案

如果您的数据框已排序:

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

dates = pd.date_range("2000-01-01", periods=48, freq="M")
df = pd.DataFrame({"Year":dates.year,
"Month":dates.month_name().str.slice(stop=3),
"Count":np.random.randint(0,100,48)})

Year Month Count
0 2000 Jan 96
1 2000 Feb 5
2 2000 Mar 97
3 2000 Apr 40
4 2000 May 55
5 2000 Jun 16

然后:

df['Month'] = pd.Categorical(df['Month'],categories=df['Month'].unique())

否则创建一个订单列表:

month_order = pd.date_range("2000-01-01", periods=12, freq="M").month_name().str.slice(stop=3)
df['Month'] = pd.Categorical(df['Month'],categories=month_order)

情节将奏效:

data= pd.pivot_table(df, values='Count', index='Year', columns='Month')
f, ax = plt.subplots(figsize=(15, 6))
sns.heatmap(data, annot=True, fmt="d", linewidths=.5, ax=ax)

enter image description here

关于python - 热图的正确顺序的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69968235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com