makarand kulkarni
makarand kulkarni

Reputation: 301

pivot dataframe using columns and values

I have data frame like

Year    Month   Date    X   Y
2015    5   1   0.21120733  0.17662421
2015    5   2   0.36878636  0.14629167
2015    5   3   0.27969632  0.37910569
2016    5   1   -1.2968733  8.29E-02
2016    5   2   -1.1575716  -0.20657887
2016    5   3   -1.0049003  -0.39670503
2017    5   1   -1.5630698  1.1710221
2017    5   2   -1.70889    0.93349206
2017    5   3   -1.8548334  0.86701781
2018    5   1   -7.94E-02   0.3962194
2018    5   2   -2.91E-02   0.39321879

I want to make it like

2015    2016    2017    2018
0.21120733  -1.2968733  -1.5630698  -7.94E-02
0.36878636  -1.1575716  -1.70889    -2.91E-02
0.27969632  -1.0049003  -1.8548334  NA

I tried using df.pivot(columns='Year',values='X') but the answer is not as expected

Upvotes: 0

Views: 39

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24314

Try passing index in pivot():

out=df.pivot(columns='Year',values='X',index='Date')
#If needed use:
out=out.rename_axis(index=None,columns=None)

OR

Try via agg() and dropna():

out=df.pivot(columns='Year',values='X').agg(sorted,key=pd.isnull).dropna(how='all')
#If needed use:
out.columns.names=[None]

output of out:

     2015       2016            2017     2018
0   0.211207    -1.296873   -1.563070   -0.0794
1   0.368786    -1.157572   -1.708890   -0.0291
2   0.279696    -1.004900   -1.854833    NaN

Upvotes: 1

Related Questions