Reshaping Long Data to Wide in Python (Pandas)

时间:2018-03-25 19:15:05

标签: python pandas dataframe reshape

I'm trying to reshape my long data to a wide format. The data currently looks like:

OBS . date . TICKER . RET

1 . 20050131 . AAPL . 0.02
2 . 20050231 . AAPL . 0.01
3 . 20050131 . GOOG . 0.05
4 . 20050231 . GOOG . 0.03

And I would like to get the data like:

TICKER . 20050131 . 20050231

AAPL   .   0.02   .   0.01
GOOG   .   0.05   .   0.03

The data is stored in a pandas dataframe. I tried stacking the data, but I don't think I'm doing it right.

Thanks for the help!

1 个答案:

答案 0 :(得分:0)

You can pivot your dataframe:

df.pivot(index='TICKER', columns='date', values='RET')

date    20050131  20050231
TICKER                    
AAPL        0.02      0.01
GOOG        0.05      0.03