gpt4 book ai didi

python - 如何在pandas中绘制图形计数表

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:32 26 4
gpt4 key购买 nike

我有一个数据框 df,其中有两列 customer1customer2,它们是字符串值。我想为这两列中的每对计数制作一个方形图形表示。

我可以

df[['customer1', 'customer2']].value_counts()

这会给我计数。但是我怎样才能做出看起来有点像的东西:

enter image description here

从结果来看?

我无法提供我的真实数据集,但这是一个玩具示例,在 csv 中包含三个标签。

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

最佳答案

更新:

Is it possible to sort the rows/columns so the highest count rows are at the top ? In this case the order would be b,a,c

IIUC 你可以这样做(哪里):

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

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

In [82]: idx
Out[82]: Index(['b', 'a', 'c'], dtype='object', name='customer1')

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

enter image description here

旧答案:

你可以使用heatmap() seaborn 模块中的方法:

In [42]: import seaborn as sns

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

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

In [45]: x
Out[45]:
customer2 a b c
customer1
a 1 1 2
b 1 0 4
c 0 0 1

In [46]: sns.heatmap(x)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0xb150b70>

enter image description here

或带有注释:

In [48]: sns.heatmap(x, annot=True)
Out[48]: <matplotlib.axes._subplots.AxesSubplot at 0xc596d68>

enter image description here

关于python - 如何在pandas中绘制图形计数表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279858/

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