title: Pandas: merge multiple rows with the same id into one row
body: <p>I have a table that looks like this:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>id</th>
  <th>id2</th>
  <th>purchase</th>
  <th>n_items</th>
  <th>amount_spent</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>yn12</td>
  <td>book</td>
  <td>4</td>
  <td>32</td>
  </tr>
  <tr>
  <td>1</td>
  <td>yn34</td>
  <td>chair</td>
  <td>2</td>
  <td>68</td>
  </tr>
  <tr>
  <td>2</td>
  <td>yn12</td>
  <td>desk</td>
  <td>1</td>
  <td>132</td>
  </tr>
  <tr>
  <td>3</td>
  <td>yn12</td>
  <td>chair</td>
  <td>8</td>
  <td>450</td>
  </tr>
  <tr>
  <td>3</td>
  <td>yn34</td>
  <td>book</td>
  <td>3</td>
  <td>54</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>What I am trying to do is to convert the table like following:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>id</th>
  <th>yn12_purchase</th>
  <th>yn34_puchase</th>
  <th>yn12_n_items</th>
  <th>yn34_n_items</th>
  <th>yn12_amount_spent</th>
  <th>yn34_amount_spent</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>book</td>
  <td>chair</td>
  <td>4</td>
  <td>2</td>
  <td>32</td>
  <td>68</td>
  </tr>
  <tr>
  <td>2</td>
  <td>desk</td>
  <td>NA</td>
  <td>1</td>
  <td>NA</td>
  <td>132</td>
  <td>NA</td>
  </tr>
  <tr>
  <td>3</td>
  <td>chair</td>
  <td>book</td>
  <td>8</td>
  <td>3</td>
  <td>450</td>
  <td>54</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>As you can see, each id can have a maximum of 2 id2. and id2s are not unique and can be repeated for each id.
  I have tried to use pivot_table and swaplevel functionalities in python like the following code, however, I am getting an error saying that &quot;TypeError: Can only swap levels on a hierarchical axis.&quot; Any idea how I can make the second table?</p>
  <p>Thank you!</p>
  <pre><code>cols = df.columns
  out = test.pivot_table(cols, &quot;id&quot;, &quot;id2&quot;).swaplevel(0, 1)
  </code></pre>