I have this df
:
Close
Symbol Date
AA 1/20/1998 29.530121
1/14/2021 25.09
AIG 1/20/1998 485.831665
1/14/2021 41.299999
AXP 1/20/1998 17.698372
... ... ...
WMT 1/14/2021 146.970001
XOM 1/20/1998 15.515985
1/14/2021 50.310001
Symbol
and Date
are indexes. There are some exceptions where there is a symbol with only 1 date (WMT in the case of this example).
I want this:
Start Date End Date Start Close End Close
Symbol
AA 1/20/1998 1/14/2021 29.530121 25.09
AIG 1/20/1998 1/14/2021 485.831665 41.299999
AXP 1/20/1998 1/14/2021 17.698372 123.78
... ... ... ... ...
VZ 1/20/1998 1/14/2021 14.96 57.040001
WMT 1/14/2021 Nan 146.970001 Nan
XOM 1/20/1998 1/14/2021 15.515985 50.310001
Other ways of dealing with the exception (WMT) are fine. I just envision taking the first date and assuming it's the start.
I found this stack overflow post which suggests pivot tables for a similar issue but I have been unable the adapt it. I have tried this:
test1 = df.reset_index()
pd.pivot_table(test1,index=['Symbol'],columns='Date',values='Close')
which returns:
Date 1998-01-20 2021-01-14
Symbol
AA 29.530121 25.090000
AIG 485.831665 41.299999
AXP 17.698372 123.779999
BA 27.150482 209.910004
... ... ...
This merges Symbol
gets Close
in the same row, but doesn't deal with the dates how I'm trying to. I've since been checking the pd.pivot_table
documentation but haven't been able to get any closer. Any suggestions, pivot_table
or otherwise?