Have you ever tried to rename a column in pandas dataframe by header. That is setting first element of column as the name of the column.
So this is the recipe on how we can rename column header of a Pandas DataFrame.
import pandas as pd
We have imported pandas which will be needed for the dataset.
We have created a dataframe with features as "0", "1", "2" and "3".
raw_data = {"0": ["first_name", "Penny", "Tina", "Jake", "Amy"],
"1": ["last_name", "Jacobson", "Raj", "Milner", "Cooze"],
"2": ["age", 52, 38, 27, 12],
"3": ["Rating_Score", 29, 51, 25, 13]}
df = pd.DataFrame(raw_data)
print(df)
So Here first we have selected the first element of the columns and stored it in header and then we have selected the rest of the elements of the dataframe. Now we are renaming the columns with the values we have stored in the header.
header = df.iloc[0]
print(header)
df = df[1:]
print(df)
df = df.rename(columns = header)
print(df)
So the output comes as:
0 1 2 3 0 first_name last_name age Rating_Score 1 Penny Jacobson 52 29 2 Tina Raj 38 51 3 Jake Milner 27 25 4 Amy Cooze 12 13 0 first_name 1 last_name 2 age 3 Rating_Score Name: 0, dtype: object 0 1 2 3 1 Penny Jacobson 52 29 2 Tina Raj 38 51 3 Jake Milner 27 25 4 Amy Cooze 12 13 first_name last_name age Rating_Score 1 Penny Jacobson 52 29 2 Tina Raj 38 51 3 Jake Milner 27 25 4 Amy Cooze 12 13