2016-09-02 39 views
0

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 

答案是

x = df.pivot_table(index='customer1',columns='customer2',aggfunc='size',fill_value=0) 
idx = x.max(axis=1).sort_values(ascending=0).index 
sns.heatmap(x[idx].reindex(idx), annot=True) 

這給出了一個正方形矩陣,顯示了兩列中每對的計數數量。

但是,如果第一列中沒有出現在第二列中的項目,此解決方案不起作用。例如:

a,b 
a,c 
c,b 

給出一個錯誤,指出[u,'a']不在索引中。

有沒有簡單的解決方案?

+1

你可以提供一個簡單的數據集,這將有助於重現問題了嗎? – MaxU

+0

這是問題底部的三條線之一。 – eleanora

+0

好的,您想要表示爲熱圖的期望__sorted__ DF是什麼? – MaxU

回答

1

試試這個:

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

+0

在這個例子中,我們需要按行順序創建列順序b,a,c。這意味着我們最終會得到一個空白欄。 – eleanora