如何在pandas中绘制一个热图,其中不包含在两列中的项目

2024-06-09 10:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

How to draw a graphical count table in pandas中,我问如何从输入数据绘制热图,例如:

customer1,customer2
a,b
a,c
a,c
b,a
b,c
b,c
c,c
a,a
b,c
b,c

答案是

^{pr2}$

这将给出一个正方形矩阵,显示两列中每对的计数数。在

但是,如果第一列中有项目在第二列中没有出现,则此解决方案不起作用。例如:

a,b
a,c
c,b

给出一个错误,说明[u,'a']不在索引中。在

有简单的解决办法吗?在


Tags: to数据答案inpandascounttable绘制
1条回答
网友
1楼 · 发布于 2024-06-09 10:29:48

试试这个:

In [129]: df
Out[129]:
  customer1 customer2
0         a         b
1         a         c
2         a         c
3         b         b
4         b         c
5         b         c
6         c         c
7         a         b
8         b         c
9         b         c

In [130]: x = df.pivot_table(index='customer1',columns='customer2',aggfunc='size',fill_value=0)

In [131]: idx = x.max(axis=1).sort_values(ascending=0).index

In [132]: cols = x.max().sort_values(ascending=0).index

In [133]: sns.heatmap(x[cols].reindex(idx), annot=True)
Out[133]: <matplotlib.axes._subplots.AxesSubplot at 0xbb22588>

enter image description here

相关问题 更多 >