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

How to re-write dataframe with new rows per column?

I have a pandas data frame that looks like the following

Name Col 1 Col 2
A 1 2
B 3 4

I’d like to change the dataset so that it has 2 columns, name and value. But I’d like to create a new row for each existing row combined with each column.

Like this:

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

Name Val
A-Col1 1
A-Col2 2
B-Col1 3
B-Col2 4

>Solution :

here is one way do it, using melt

df2=df.melt(id_vars='Name')
df2['Name'] = df2['Name'] + '-' + df2['variable']
df2=df2.drop(columns='variable')
df2
    Name    value
0   A-Col 1     1
1   B-Col 1     3
2   A-Col 2     2
3   B-Col 2     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