-1

I need to extract data from stock prices and I have build a code which provides me the values in below format: enter image description here

But I need this data to be in the format below enter image description here

sunny3884
  • 1
  • 1
  • also https://stackoverflow.com/questions/49479902/reshaping-long-data-to-wide-in-python-pandas and https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe – Stuart Jun 02 '21 at 20:44

2 Answers2

1

Try:

df_in = pd.DataFrame({'Volume': [12575, 5630, 240],
                  'High': [148] * 3,
                  'Time': ['4:15', ' 5:30', '6:30']})

df_in.index = df_in.index + 1

df_out = df_in.stack().to_frame().T

df_out.columns = [f'{j}{i}' for i, j in df_out.columns]

df_out

Output:

  Volume1 High1 Time1 Volume2 High2  Time2 Volume3 High3 Time3
0   12575   148  4:15    5630   148   5:30     240   148  6:30
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
1

Input data:

df = pd.DataFrame({"Volume": [12575, 5630, 2430], "High": [148, 148, 148], "Time": ["4:15", "5:30", "6:30"]}, index=[1, 2, 3])
idx = pd.MultiIndex.from_product([df.columns, df.index.astype(str)]).map(''.join)

df = df.unstack().to_frame().set_index(idx).transpose()

Output result

>>> df
  Volume1 Volume2 Volume3 High1 High2 High3 Time1 Time2 Time3
0   12575    5630    2430   148   148   148  4:15  5:30  6:30

Updated following @HenryEcker's comment

Corralien
  • 109,409
  • 8
  • 28
  • 52
  • [`Index.map`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.map.html#pandas-index-map) is another option to flatten the index directly from the MultiIndex instead of `to_flat_index().str.join()`. `pd.MultiIndex.from_product(...).map(''.join)` – Henry Ecker Jun 02 '21 at 21:27