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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.