使用seaborn热图 [英] Using seaborn heatmap

查看:59
本文介绍了使用seaborn热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Seaborn中使用热图遇到了一些问题

I am running into some issues using heatmap in seaborn

代码:

df[['latitude', 'longitude', 'interest_level']]
a = df.pivot('latitude', 'longitude', 'interest_level')

错误:

ValueError: Index contains duplicate entries, cannot reshape

兴趣级别有多个重复值.我设想的是,经/纬度将形成一个2D图,兴趣水平是地图中的值.兴趣水平是分类的,只有 3 个唯一值.

Interest level has multiple duplicate values. What i am envisioning is that the lat/long would form a 2D diagram, with the interest level being the value in the map. Interest level is categorical with only 3 unique values.

我正在按照seaborn热图教程 http:/来使用错误的类吗?/seaborn.pydata.org/generated/seaborn.heatmap.html

Am i using the wrong class as i am following the seaborn heatmap tutorial http://seaborn.pydata.org/generated/seaborn.heatmap.html

推荐答案

您需要 数据透视表 ,具有一些汇总功能,例如 mean sum ,...:

You need pivot_table with some aggregate function like mean, sum, ...:

#subset for pivot_table or groupby solution is not necessary, you can omit it
#df = df[['latitude', 'longitude', 'interest_level']]
a = df.pivot_table(index='latitude', 
                   columns='longitude', 
                   values='interest_level', 
                   aggfunc='mean')

groupby ,聚合函数并unstack:

Or groupby, aggregate function and unstack:

a = df.groupby(['latitude','longitude'])['interest_level'].mean().unstack()

示例:

df = pd.DataFrame({'latitude':[53,54,55,55],
                    'longitude':[10,11,12,12],
                    'interest_level':[1,5,2,6],
                    'another_col':[4,7,4,2]})
print (df)
   another_col  interest_level  latitude  longitude
0            4               1        53         10
1            7               5        54         11
2            4               2        55         12 <-duplicates for 55,12
3            2               6        55         12 <-duplicates for 55,12

a = df.pivot_table(index='latitude', 
                   columns='longitude', 
                   values='interest_level', 
                   aggfunc='mean')
print (a)
longitude   10   11   12
latitude                
53         1.0  NaN  NaN
54         NaN  5.0  NaN
55         NaN  NaN  4.0 <- (2+6)/2 = 4

最后一个:

ax = sns.heatmap(a)

这篇关于使用seaborn热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆