How to swap columns conditionally in pandas
<p>I have a pandas dataframe  <code>df</code> with 4 columns. For example here is a toy example:</p>

<pre><code>foo1    foo2     foo3  foo4
egg     cheese   2     1
apple   pear     1     3
french  spanish  10    1
</code></pre>

<p>The columns are foo1, foo2, foo3 and foo4</p>

<p>I would like to swap columns foo1 and foo2 and also swap columns foo3 and foo4 when foo3 &lt; foo4.  So the result would be:</p>

<pre><code>foo1     foo2    foo3  foo4
cheese   egg     1     2
apple    pear    1     3
spanish  french  1     10
</code></pre>

<p>I can find the rows that need swapping with <code>df[df['foo3'] &lt; df['foo4']]</code>  but how can I do the swapping efficiently. My dataframe is large.</p>

<p>You can find the rows with <code>df[df['foo3'] &lt; df['foo4']]</code>, yes, but if you use the Boolean series instead, you can easily accomplish your goal:</p>

<pre><code>s = df['foo3'] &lt; df['foo4']
df.loc[s, ['foo1','foo2']] = df.loc[s, ['foo2','foo1']].values
df.loc[s, ['foo3','foo4']] = df.loc[s, ['foo4','foo3']].values
</code></pre>

<p>Note, you need the <code>.values</code> at the end of the RHS to prevent Pandas from aligning on column names, which will undermine the purpose.</p>

python pandas