lrh09
lrh09

Reputation: 587

pandas years of data in database convert to years in columns

With a df as below:

    name    year    total
0   A   2015    100
1   A   2016    200
2   A   2017    500
3   C   2016    400
4   B   2016    100
5   B   2015    200
6   B   2017    800

How do I create a new dataframe with years as columns and amount as values:

Name   2015   2016   2017
A      100    200    500
B      200    100    800
C      0      400    0

Upvotes: 0

Views: 42

Answers (1)

BENY
BENY

Reputation: 323226

UMMM pivot with fillna

df.pivot(*df.columns).fillna(0).reset_index()
Out[815]: 
year name   2015   2016   2017
0       A  100.0  200.0  500.0
1       B  200.0  100.0  800.0
2       C    0.0  400.0    0.0

Upvotes: 1

Related Questions