0

In Python I would like to convert a matrix style dataframe (with many columns) to a simple three column table. Similar as below ... what's the easiest way?

From

day col1 col2 col3 ... col554
2022-01-01 3 5 7 ... 0
2022-01-02 4 8 3 ... 2

To

day col value
2022-01-01 col1 3
2022-01-01 col2 5
2022-01-01 col3 7
... ... ...
2022-01-01 col554 0
2022-01-02 col1 4
2022-01-02 col2 8
2022-01-02 col3 3
... ... ...
2022-01-02 col554 2
auato
  • 33
  • 8
  • 1
    Easiest is [melt](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.melt.html) `new_df = df.melt(id_vars='day', var_name='col')` or the long way with [set_index](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html) + [stack](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.stack.html) `new_df = df.set_index('day').rename_axis(columns='col').stack().reset_index(name='value')` both options covered in the linked canonical. – Henry Ecker Jan 18 '22 at 22:06

0 Answers0