Given this pandas dataframe where for each date and field there's a value:
df = pd.DataFrame({
'date' : [datetime(2021,3,11), datetime(2021,3,11),
datetime(2021,3,12), datetime(2021,3,12),
datetime(2021,3,13), datetime(2021,3,13)],
'field': ['A', 'B', 'A', 'B', 'A', 'B'],
'value': [150, 140, 130, 280, 260, 120]
})
date field value
0 2021-03-11 A 150
1 2021-03-11 B 140
2 2021-03-12 A 130
3 2021-03-12 B 280
4 2021-03-13 A 260
5 2021-03-13 B 120
I need to transpose it where each date is a row, and each field is a column:
df2 = pd.DataFrame({
'date' : [datetime(2021,3,11),
datetime(2021,3,12),
datetime(2021,3,13)],
'A': [150, 130, 260],
'B': [140, 280, 120]
})
date A B
0 2021-03-11 150 140
1 2021-03-12 130 280
2 2021-03-13 260 120
Note that:
- Each date is a row
- The number of fields is variable (in the example the number of fields is two, A and B)
- The content of column
value
is converted to the content of each new generated column.
Is this possible to do without iterrows()
?