0

I was wondering if you could help me with the following scenario. I have a pandas DataFrame that is similar to this one:

df_existing = pd.DataFrame({'date': ['2022-10-01', '2022-10-02'],
                            'a_v1': [1, 7],
                            'a_v2': [2, 8],
                            'a_v3': [3, 9],
                            'b_v1': [4, 10],
                            'b_v2': [5, 11],
                            'b_v3': [6, 12]})

I would like to turn said DataFrame into this:

df_desired = pd.DataFrame({'date': ['2022-10-01', '2022-10-01', 
                                    '2022-10-02', '2022-10-02'],
                           'group': ['a', 'b', 'a', 'b'],
                           'v1': [1, 4, 7, 10],
                           'v2': [2, 5, 8, 11],
                           'v3': [3, 6, 9, 12]})

I tried to adapt online examples that rely on melt to turn data from wide to long format but could not shape the data accordingly.

I would be most grateful if you could help me reshape the DataFrame.

Thank you!

user1352042
  • 47
  • 3
  • 6

0 Answers0