How To Combine Multiple Rows Into One Based on Shared Value in Pandas
<p>I have a dataframe that generically looks like this: </p>

<pre><code>df = pd.DataFrame({'Country': ['USA', 'USA', 'Canada', 'Canada'], 'GDP':          [45000, 68000, 34000, 46000], 'Education': [5, 3, 7, 9]})
</code></pre>

<p>Giving: </p>

<pre><code>    Country  Education    GDP
0     USA          5    45000
1     USA          3    68000
2  Canada          7    34000
3  Canada          9    46000
</code></pre>

<p>I'd like to have all the values for each country listed on the same row, so it reads:</p>

<pre><code>Country    Education    Education    GDP        GDP
USA         5            3           45000      68000
</code></pre>

<p>How does one accomplish this?  </p>

<p>And yes, some of the columns do have the same name.</p>

<p>Thank you.</p>

<p>The output that you want generally leads to loss of information.</p>

<pre><code>Country    Education    Education    GDP        GDP
USA         5            3           45000      68000
</code></pre>

<p>In the above case you would need to keep track of which GDP column corresponds to which Education column.</p>

<p>If you are not adamant about keeping it in this form, you can form a pivot table:</p>

<pre><code>df2=df.pivot(index='Country',columns='Education',values='GDP').reset_index()
</code></pre>

<p>This makes each unique value of the education as a column and the value of that column will be the corresponding GDP value.</p>

<pre><code>Education Country        3        5        7        9
0          Canada      NaN      NaN  34000.0  46000.0
1             USA  68000.0  45000.0      NaN      NaN
</code></pre>

<p>A better looking output can be obtained by:</p>

<pre><code>df2=df.pivot(index='Country',columns='Education',values='GDP').reset_index().set_index('Country')
</code></pre>

<p>which yields</p>

<pre><code>Country        3           5         7            9
Canada                            34000.0       46000.0
USA         68000.0     45000.0     
</code></pre>

python pandas