在Pandas数据框上逐列应用Seaborn热图 [英] Apply seaborn heatmap columnwise on pandas dataframe

查看:79
本文介绍了在Pandas数据框上逐列应用Seaborn热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在枢纽化的熊猫数据框上使用seaborn的热图表格,例如在超链接中有效

I was trying to use a heatmap form seaborn on a pivoted pandas dataframe like in the hyperlink which works

df = pd.DataFrame(np.random.randint(1,100,size = (3,2)))
df.columns = ['A','B']
df
sns.heatmap(df, annot=True, fmt="d", linewidths=.5,cmap="RdYlGn")

代码块的输出-整个数据帧都格式化为单个热图
输出选择45(最小)和86(最大),并对整个数据框进行颜色编码

Output of code block - Entire Dataframe formatted as single heatmap The output picks 45 as min and 86 as max and color codes the entire dataframe

但是我无法做到的是将热图列明智地应用到
,例如有条件的格式逐列而不是整个数据框应用。就像在此超链接的示例中一样-

But what i was unable to do was to apply the heatmap column wise i.e. like conditional formatting applied column by colummn instead of for the whole dataframe. like in the example in this hyperlink -

需要/期望的输出

对于col1,选择45的最小值和最大值88并对其进行格式化,对于col2 70&
分别选择了86个条件格式化的列,但仍显示为表格。
。在示例中,我看到了df的其余部分都设为零,并且仅格式化了1列,或者整个数据帧都进行了格式化

For col1 the min of 45 and and max of 88 is picked and formatted , for col2 70 & 86 are picked respectively Conditional formatted column wise but still displayed as a table. . In the examples i saw either the rest of the df was made to zeroes and only 1 column was formatted or the whole dataframe got the formatting

任何人都可以帮忙吗

推荐答案

您还可以将每列的最小比例缩放为零,最大比例为1,将其传递给热图,并使用

You can also scale each column to a min of zero and max of 1, pass that to the heatmap, and annotate with the original values.

scaled_df = (df - df.min(axis=0))/(df.max(axis=0) - df.min(axis=0))
sns.heatmap(scaled_df, annot=df, fmt="d", linewidths=.5, cmap="RdYlGn")

请注意,您可能要使用 cbar = False 删除颜色栏。解决方案必然要求每列具有不同的比例。

Note that you will likely want to remove the colorbar with cbar=False since the solution necessarily requires different scales for each column.

或者,可以使用 sklearn.preprocessing.minmax_scale 代替手动缩放。

Alternately, sklearn.preprocessing.minmax_scale can be used instead of scaling manually.

from sklearn.preprocessing import minmax_scale

scaled_df = minmax_scale(df)
sns.heatmap(scaled_df, annot=df, fmt="d", linewidths=.5, cmap="RdYlGn")

这篇关于在Pandas数据框上逐列应用Seaborn热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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