I have a dataframe of price data that looks like the following: (with more than 10,000 columns)
| Unamed: 0 | 01973JAC3 corp | Unamed: 2 | 019754AA8 corp | Unamed: 4 | 01265RTJ7 corp | Unamed: 6 | 01988PAD0 corp | Unamed: 8 | 019736AB3 corp | |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 2004-04-13 | 101.1 | 2008-06-16 | 99.1 | 2010-06-14 | 110.0 | 2008-06-18 | 102.1 | NaT | NaN |
| 2 | 2004-04-14 | 101.2 | 2008-06-17 | 100.4 | 2010-07-05 | 110.3 | 2008-06-19 | 102.6 | NaT | NaN |
| 3 | 2004-04-15 | 101.6 | 2008-06-18 | 100.4 | 2010-07-12 | 109.6 | 2008-06-20 | 102.5 | NaT | NaN |
| 4 | 2004-04-16 | 102.8 | 2008-06-19 | 100.9 | 2010-07-19 | 110.1 | 2008-06-21 | 102.6 | NaT | NaN |
| 5 | 2004-04-19 | 103.0 | 2008-06-20 | 101.3 | 2010-08-16 | 110.3 | 2008-06-22 | 102.8 | NaT | NaN |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | NaT | NaN |
| 3431 | NaT | NaN | 2021-12-30 | 119.2 | NaT | NaN | NaT | NaN | NaT | NaN |
| 3432 | NaT | NaN | 2021-12-31 | 119.4 | NaT | NaN | NaT | NaN | NaT | NaN |
(Those are 9-digit CUSIPs in the header. So every two columns represent date and closed price for a security.) I would like to
- find and get rid of empty pairs of date and price like "Unamed: 8" and"019736AB3 corp"
- then rearrange the dateframe to a panel of monthly close price as following:
| Date | 01973JAC3 | 019754AA8 | 01265RTJ7 | 01988PAD0 |
|---|---|---|---|---|
| 2004-04-30 | 102.1 | NaN | NaN | NaN |
| 2004-05-31 | 101.2 | NaN | NaN | NaN |
| ... | ... | ... | ... | ... |
| 2021-12-30 | NaN | 119.2 | NaN | NaN |
| 2021-12-31 | NaN | 119.4 | NaN | NaN |
Edit: I wanna clarify my question.
So my dataframe has more than 10,000 columns, which makes it impossible to just drop by column names or change their names one by one. The pairs of date and price start and end at different time and are of different length (, and of different frequency). I m looking for an efficient way to arrange therm into a less messy form. Thanks.
Here is a sample of 30 columns. https://github.com/txd2x/datastore file name: sample-question2022-01.xlsx
I figured out: stacking and then reshaping.Thx for the help.
for i in np.arange(len(price.columns)/2):
temp =DataFrame(columns = ['Date', 'ClosedPrice','CUSIP'])
temp['Date'] = price.iloc[ 0:np.shape(price)[0]-1, int(2*i)]
temp['ClosedPrice'] = price.iloc[0:np.shape(price)[0]-1, int(2*i+1)]
temp['CUSIP'] =price.columns[int(i*2+1)][:9] #
df = df.append(temp)
#use for loop to stack all the column pairs
df = df.dropna(axis=0, how = 'any') # drop nan rows
df = df.pivot(index='Date', columns = 'CUSIP', values = 'ClosedPrice') #reshape dataframe to have Date as index and CUSIP and column headers
df_monthly=df.resample('M').last() #finding last price of the month