Reputation: 73
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"]
})
Upvotes: 1
Views: 831
Reputation: 1933
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))
)
Upvotes: 0
Reputation: 3369
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
Upvotes: 5