Pandas 数据帧到 Seaborn
Pandas DataFrame to Seaborn
我正在尝试使用 pandas DataFrame 绘制 seaborn 热图。
我的数据格式如下
visit_table
yyyymm visit_cnt
0 201101 91252
1 201102 140571
2 201103 141457
3 201104 147680
4 201105 154066
...
68 201609 591242
69 201610 650174
70 201611 507579
71 201612 465218
如何将 DataFrame 更改为 seaborn 数据格式,如下所示
2011 2012 2013 2015
1 91252
2 14057
3 147680
4 154066
...
11 123455
12 1234456
如有必要,您可以使用 to_datetime
for converting the column yyyymm
and then create new Series
(columns) with dt.month
and dt.year
. Last reshape by pivot
and replace NaN
to 0
by fillna
。
df['yyyymm'] = pd.to_datetime(df['yyyymm'], format='%Y%m')
df1 = pd.pivot(index=df['yyyymm'].dt.month, columns=df['yyyymm'].dt.year, values=df.visit_cnt)
.fillna(0)
print (df1)
yyyymm 2011 2016
yyyymm
1 91252.0 0.0
2 140571.0 0.0
3 141457.0 0.0
4 147680.0 0.0
5 154066.0 0.0
9 0.0 591242.0
10 0.0 650174.0
11 0.0 507579.0
12 0.0 465218.0
另一种解决方案类似,仅通过 set_index
and unstack
:
重塑
df['yyyymm'] = pd.to_datetime(df['yyyymm'], format='%Y%m')
df['year'] = df['yyyymm'].dt.year
df['month'] = df['yyyymm'].dt.month
df1 = df.set_index(['month','year'])['visit_cnt'].unstack(fill_value=0)
print (df1)
year 2011 2016
month
1 91252 0
2 140571 0
3 141457 0
4 147680 0
5 154066 0
9 0 591242
10 0 650174
11 0 507579
12 0 465218
最后,使用seaborn.heatmap
:
import seaborn as sns
ax = sns.heatmap(df1)
我正在尝试使用 pandas DataFrame 绘制 seaborn 热图。 我的数据格式如下
visit_table
yyyymm visit_cnt
0 201101 91252
1 201102 140571
2 201103 141457
3 201104 147680
4 201105 154066
...
68 201609 591242
69 201610 650174
70 201611 507579
71 201612 465218
如何将 DataFrame 更改为 seaborn 数据格式,如下所示
2011 2012 2013 2015
1 91252
2 14057
3 147680
4 154066
...
11 123455
12 1234456
如有必要,您可以使用 to_datetime
for converting the column yyyymm
and then create new Series
(columns) with dt.month
and dt.year
. Last reshape by pivot
and replace NaN
to 0
by fillna
。
df['yyyymm'] = pd.to_datetime(df['yyyymm'], format='%Y%m')
df1 = pd.pivot(index=df['yyyymm'].dt.month, columns=df['yyyymm'].dt.year, values=df.visit_cnt)
.fillna(0)
print (df1)
yyyymm 2011 2016
yyyymm
1 91252.0 0.0
2 140571.0 0.0
3 141457.0 0.0
4 147680.0 0.0
5 154066.0 0.0
9 0.0 591242.0
10 0.0 650174.0
11 0.0 507579.0
12 0.0 465218.0
另一种解决方案类似,仅通过 set_index
and unstack
:
df['yyyymm'] = pd.to_datetime(df['yyyymm'], format='%Y%m')
df['year'] = df['yyyymm'].dt.year
df['month'] = df['yyyymm'].dt.month
df1 = df.set_index(['month','year'])['visit_cnt'].unstack(fill_value=0)
print (df1)
year 2011 2016
month
1 91252 0
2 140571 0
3 141457 0
4 147680 0
5 154066 0
9 0 591242
10 0 650174
11 0 507579
12 0 465218
最后,使用seaborn.heatmap
:
import seaborn as sns
ax = sns.heatmap(df1)