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

Transpose and keep a column name

I have a dataframe with the following information:

data = {'Code':['xxy','zzy', 'rrr'], 
        'Service':["23a","22c","21d"],
        'Service2':["44e", "32c","85a"],
        'Service3':["42e", "32z","8m"],
       }
df = pd.DataFrame(data)
df

It looks like this
table

and i would like it to look 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

expected

please your help, thanks!

>Solution :

df.set_index('Code').stack().reset_index()[['Code', 0]]

result:

   Code 0
0   xxy 23a
1   xxy 44e
2   xxy 42e
3   zzy 22c
4   zzy 32c
5   zzy 32z
6   rrr 21d
7   rrr 85a
8   rrr 8m

if you want change column name, use following code(including full code):

df.set_index('Code').stack().reset_index()[['Code', 0]].rename(columns={0:'as you wish'})


    Code    as you wish
0   xxy     23a
1   xxy     44e
2   xxy     42e
3   zzy     22c
4   zzy     32c
5   zzy     32z
6   rrr     21d
7   rrr     85a
8   rrr     8m
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