1

My dataFrame looks like this :

+---------------+------+--------+
|     Date      | Type | Number |
+---------------+------+--------+
| 14-March-2020 | A    |     10 |
| 14-March-2020 | B    |     20 |
| 14-March-2020 | C    |     30 |
| 15-March-2020 | A    |     40 |
| 15-March-2020 | B    |     50 |
| 15-March-2020 | C    |     60 |
+---------------+------+--------+

I want to transform it to :

+---------------+----+----+----+
|     Date      | A  | B  | C  |
+---------------+----+----+----+
| 14-March-2020 | 10 | 20 | 30 |
| 15-March-2020 | 40 | 50 | 60 |
+---------------+----+----+----+

I have tried using df.groupby('Date') - for an initial condensation - however that doesn't seem to work. Any help would be great.

  • Does this answer your question? [How to pivot a dataframe](https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe). Use `df.pivot('Date', 'Type', 'Number')` – Shubham Sharma Jul 28 '20 at 15:23
  • Thanks, this answered most of my question. However, there remains a small issue with indexing. I used df.reset_index(inplace=True) but still, there remains a column named 'Type' to the left of the required columns. It contains the indexes true, but it's probably not the "index" in the conventional sense of a dataframe. – Debapratim Chakraborty Jul 28 '20 at 17:06

1 Answers1

1

A solution that removes also the index 'Type' that remains after pivoting the dataframe involves rename_axis after resetting the index.

import pandas as pd
df.pivot('Date', 'Type', 'Number').reset_index().rename_axis(columns={'Type': ''})

#             Date   A   B   C
# 0  14-March-2020  10  20  30
# 1  15-March-2020  40  50  60

If we omit rename_axis, we in fact obtain

df.pivot('Date', 'Type', 'Number').reset_index()
# Type            Date   A   B   C
# 0      14-March-2020  10  20  30
# 1      15-March-2020  40  50  60
Ric S
  • 9,073
  • 3
  • 25
  • 51