How to draw a graphical count table in pandas
<p>I have a dataframe df with two columns <code>customer1</code> and <code>customer2</code> which are string valued.  I would like to make a square graphical representation of the count  number for each pair from those two columns.   </p>

<p>I  can do</p>

<pre><code>df[['customer1', 'customer2']].value_counts()
</code></pre>

<p>which will give me the counts.  But how can I make something that looks a little like:</p>

<p><a href="http://i.stack.imgur.com/GZ6yI.png" rel="nofollow"><img src="http://i.stack.imgur.com/GZ6yI.png" alt="enter image description here"></a> </p>

<p>from the result?</p>

<p>I can't provide my real dataset  but here is a toy example with three labels in csv.</p>

<pre><code>customer1,customer2
a,b
a,c
a,c
b,a
b,c
b,c
c,c
a,a
b,c
b,c
</code></pre>

<p><strong>UPDATE:</strong>  </p>

<blockquote>
  <p>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</p>
</blockquote>

<p>IIUC you can do it this way (where ):</p>

<pre><code>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]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x9ee3f98&gt;
</code></pre>

<p><a href="http://i.stack.imgur.com/sIVen.png" rel="nofollow"><img src="http://i.stack.imgur.com/sIVen.png" alt="enter image description here"></a></p>

<p><strong>OLD answer:</strong></p>

<p>you can use <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html" rel="nofollow">heatmap()</a> method from <code>seaborn</code> module:</p>

<pre><code>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]: &lt;matplotlib.axes._subplots.AxesSubplot at 0xb150b70&gt;
</code></pre>

<p><a href="http://i.stack.imgur.com/YMVgk.png" rel="nofollow"><img src="http://i.stack.imgur.com/YMVgk.png" alt="enter image description here"></a></p>

<p>or with annotations:</p>

<pre><code>In [48]: sns.heatmap(x, annot=True)
Out[48]: &lt;matplotlib.axes._subplots.AxesSubplot at 0xc596d68&gt;
</code></pre>

<p><a href="http://i.stack.imgur.com/dN2YV.png" rel="nofollow"><img src="http://i.stack.imgur.com/dN2YV.png" alt="enter image description here"></a></p>

python pandas