How to draw a heatmap in pandas with items that don't occur in both columns
<p>In <a href="http://stackoverflow.com/questions/39279858/how-to-draw-a-graphical-count-table-in-pandas">How to draw a graphical count table in pandas</a> I asked how to draw a heatmap from input data such as:</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>The answer was</p>

<pre><code>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)
</code></pre>

<p>This gives a square matrix showing the number of counts for each pair from the two columns.</p>

<p>This solution doesn't work however if there items in the first column which don't appear in the second. For example:</p>

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

<p>Gives an error saying that [u,'a'] is not in the Index.</p>

<p>Is there a simple solution?</p>

<p>Try this:</p>

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

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

python pandas seaborn