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

Making wide-to-long transformation based on the values of a column

I need to make a wide-to-long transformation using Pandas.

Considering the given dataframe input :

import pandas as pd
df = pd.DataFrame({'Id': ['AA', 'BB', 'CC'], 'Value': [4, 2, 3]})

>>> df

enter image description here

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’m looking for a way to have this kind of output :

enter image description here

I tried to make a list (from 1 to the value of the second column) but I got the error below :

df['pos'] = df.apply(list(range(1, df['Value'])))
df.explode('pos')

TypeError: ‘Series’ object cannot be interpreted as an integer

Do you know you have to fix that or any other suggestions to make this transformation work ?

>Solution :

You can turn Value column into list then explode

out = (df.assign(Value=df['Value'].apply(lambda x: range(1, x+1)))
       .explode('Value', ignore_index=True))
print(out)

   Id Value
0  AA     1
1  AA     2
2  AA     3
3  AA     4
4  BB     1
5  BB     2
6  CC     1
7  CC     2
8  CC     3
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