How to add columns names as first row to DataFrame?

Question:

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"]
                 })
Asked By: Jack Miller

||

Answers:

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
Answered By: nikeros

You can use agg() to create a DataFrame with its column names as a row and then concat() this with the original DataFrame:

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([df.agg([lambda ser: ser.name]), df], ignore_index=True)

The advantage of this is that it can be used in method chaining if you like, e.g.:

import pandas as pd

df = (pd.DataFrame({"Sales QTY": [10, 20, 30, 40],
                   "Sales Person": ['Jack', 'Adam', 'Ken', 'Jack'],
                   "Product": ["Apple", "Orange", "Apple", "Cherry"]
                   })
      .pipe(lambda df_: pd.concat([df_.agg([lambda ser: ser.name]), df_], ignore_index=True))
      )
Answered By: mouwsy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.