compare all adjacent columns in a dataframe
<p>I have the following dataframe</p>

<pre><code>df = pd.DataFrame(np.random.choice(list('xyz'), (5, 4)), columns=list('ABCD'))

print df

   A  B  C  D
0  x  z  x  z
1  y  z  x  z
2  y  z  x  x
3  y  y  y  x
4  y  x  z  z
</code></pre>

<p>I'd like to compare columns <code>A</code> with <code>B</code>, <code>B</code> with <code>C</code>, and <code>C</code> with <code>D</code>.<br>
I know I can do <code>df.A == df.B</code>, but is there a way to easily compare all columns with their adjacent columns?</p>

<p>I'd like to see</p>

<pre><code>       B      C      D
0  False  False  False
1  False  False  False
2  False  False   True
3   True   True  False
4  False  False   True
</code></pre>

<p>I've tried this</p>

<pre><code>pd.concat([df.iloc[:, i] == df.iloc[:, i+1] for i in range(df.shape[1]-1)], axis=1, keys=df.columns.tolist()[1:])
</code></pre>

<p>Which is how I got the desired output.  Efficiency is important, so I feel my attempt is inadequate.  If these were <code>float</code>s or <code>int</code>s, I could</p>

<pre><code>df.diff(axis=1) == 0
</code></pre>

<p>But they're strings</p>

<p>Use <code>shift(axis=1)</code></p>

<pre><code>(df == df.shift(axis=1)).iloc[:, 1:]
</code></pre>

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

python pandas