-2

I have pandas dataframe which i would like to be sliced after every 4 columns and then vertically stacked on top of each other which includes the date as index.Is this possible by using np.vstack()? Thanks in advance!

ORIGINAL DATAFRAME

Please refer the image for the dataframe. I want something like this

WANT IT MODIFIED TO THIS

1 Answers1

0

Until you provide a Minimal, Complete, and Verifiable example, I will not test this answer but the following should work:

given that we have the data stored in a Pandas DataFrame called df, we can use pd.melt

moltendfs = []
for i in range(4):
    moltendfs.append(df.iloc[:, i::4].reset_index().melt(id_vars='date'))
newdf = pd.concat(moltendfs, axis=1)

We use iloc to take only every fourth column, starting with the i-th column. Then we reset_index in order to be able to keep the date column as our identifier variable. We use melt in order to melt our DataFrame. Finally we simply concatenate all of these molten DataFrames together side by side.

tobsecret
  • 2,442
  • 15
  • 26
  • my_list_1=[] for i in range(4): my_list_1.append(securities_df_final.iloc[:,i::4].reset_index().melt(id_vars='Date')) new_df=pd.concat(my_list_1,axis=1) – alan centaur Apr 18 '18 at 18:09
  • got an error running the above code KeyError: 'Date' I have got Date as one of the columns – alan centaur Apr 18 '18 at 18:12
  • Again, provide a testable snippet of code, so I can reproduce your problem. Without part of your DataFrame, it will be hard for me to do that – tobsecret Apr 18 '18 at 19:17
  • You may find this answer from a question about how to do that for pandas questions useful: https://stackoverflow.com/a/32536193/7480990 – tobsecret Apr 18 '18 at 21:28