Home > OS >  How to add columns names as first row to DataFrame?
How to add columns names as first row to DataFrame?

Time:09-12

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"]
                 })

CodePudding user response:

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
  • Related