Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas merge columns and adding the original column

I have a Dataframe with value predictions.

The first column is for the exact value and each new column is a week in the future. For each week a new row is added.
As a result, I have the following example table:

Index W1  W2  W3  W4
1.     5   7   4   9
2.     8   7  10  11

and so on.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want the values to all be in a single row and I want the other rows to be the number of weeks ahead (in my case exactly the column index of the value).

My table should look like this:

Index Value Week
1.        5    1
2.        7    2
3.        4    3 
4.        9    4
5.        8    1
6.        7    2 
7.       10    3
8.       11    4

I am working with python and have just declared the dataframe. How can this be done?

>Solution :

This is a variation on melt:

(df.melt(id_vars='Index', value_name='Value')
   .assign(Week=lambda d: d['variable'].str[1:].astype(int))
   .drop(columns='variable')
   .sort_values('Index')
)

output:

   Index  Value  Week
0    1.0      5     1
2    1.0      7     2
4    1.0      4     3
6    1.0      9     4
1    2.0      8     1
3    2.0      7     2
5    2.0     10     3
7    2.0     11     4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading