Search code examples
pythonpandasdataframepivot-table

How to stack the dataframe rows into different columns


I have data in the following format:

| depth | density | tb10 | tb18 |
|-------|---------|------|------|
|   1   |   10    |  210 |  220 |
|   2   |   10    |  245 |  255 |
|   3   |   10    |  275 |  285 |
|   4   |   10    |  295 |  305 |
|   1   |   20    |  215 |  225 |
|   2   |   20    |  250 |  260 |
|   3   |   20    |  280 |  290 |
|   4   |   20    |  300 |  310 |

however, i want the data in the following way.

| depth | density | den10_tb10 | den10_tb18 | den20_tb10 | den20_tb18|
|-------|---------|------      |------      |------      |------     |
|   1   |   10    |  210       |  220       |    215     |   225     |           
|   2   |   10    |  245       |  255       |    250     |   260     |
|   3   |   10    |  275       |  285       |    280     |   290     |
|   4   |   10    |  295       |  305       |    300     |   310     |

I tried pivot table, but could not do it properly.


Solution

  • You can do so using Pivot table

    df_pivoted= df.pivot(index='depth', columns='density')
    df_pivoted.columns = [f'den{den}_{col}' for col, den in df_pivoted.columns]
    

    You can always get exactly the same output by reordering the columns, even though you don't need to do this if you gonna use your dataframe in further operations.

    df_pivoted = df_pivoted[['den10_tb10', 'den10_tb18', 'den20_tb10', 'den20_tb18']]