title: Swap values of two columns of dataframe if conditions apply (Python 3)
body: <p>I want to calculate the average of countX for all rows that have similar address1 and address2 or for the cases where the address values are inverted. That is, address1=ad3 and address2=ad1 is similar to address1=ad1 and address2=ad3.</p>
  
  <p>For instance,
  If the input is (csv file):</p>
  
   
  
  <pre><code>ID    COUNTX     ADDRESS1     ADDRESS2  
  1        21       ad3       ad1
  2        22       ad1       ad3
  3        23       ad2       ad4
  4        25       ad2       ad4
  5        25       ad1       ad5
  6        23       ad5       ad1
  7        22       ad1       ad4
  8        21       ad4       ad6  
  </code></pre>
  
  <p>The output should be:</p>
  
   
  
  <pre><code>ID    COUNTX     ADDRESS1     ADDRESS2     AVG_cOUNTX   
  1        21       ad3       ad1       21.5
  3        23       ad2       ad4       24
  5        25       ad1       ad5       24
  7        22       ad1       ad4       22
  8        21       ad4       ad6       21
  </code></pre>
  
  <p>I have tried to do the following:</p>
  
  <ol>
  <li>Use a nested loop, to swap the column values when I find that address1_of_a_row =address2_another_row and address2_of_a_row=address1_another_row</li>
  <li>Group by address1 and address2 and calculate AVG.</li>
  </ol>
  
  <p>Since I have large datasets (1-3 million), this needs to be very efficient (which is not the case for my code).</p>
  
  <p>I am using Python 3.7 and the pandas package 0.22.
  Any feedback would be appreciated.</p>