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 add columns names as first row to DataFrame?

I have a DataFrame like one given below. I want to add it’s columns names as first row to the same DataFrame. I tried to concatenate it with itself but it didn’t work/ how can I do it to get result as in desired output?

import pandas as pd
df=pd.DataFrame({"Sales QTY":[10,20,30,40],
                 "Sales Person":['Jack', 'Adam', 'Ken', 'Jack'],
                 "Product":["Apple", "Orange","Apple","Cherry"]
                 })
df=pd.concat([pd.DataFrame(df.columns),df])
df

desired output
df=pd.DataFrame({"Sales QTY":['Sales QTY', 10,20,30,40],
                 "Sales Person":["Sales Person", 'Jack', 'Adam', 'Ken', 'Jack'],
                 "Product":["Product", "Apple", "Orange","Apple","Cherry"]
                 })

>Solution :

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

A possible solution could be:

df.loc[-1] = df.columns
print(df.sort_index().reset_index(drop=True))

OUTPUT

Sales QTY  Sales Person  Product
0  Sales QTY  Sales Person  Product
1         10          Jack    Apple
2         20          Adam   Orange
3         30           Ken    Apple
4         40          Jack   Cherry
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