Home > Enterprise >  In Pandas can I replace the first row as the header?
In Pandas can I replace the first row as the header?

Time:02-25

I'm processing a data frame, and there's a challenge in the source where the data frame headers are incorrect. I want to replace the titles with the value in the first row. Here's a example:

import pandas as pd
inp = [{'c1':'age', 'c2':'weight'}, {'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)

   c1   c2
0  age weight
1  10  100
2  11  110
3  12  120

In the above, the headers are c1, c2 but I want to replace them with age, weight. Is that possible?

CodePudding user response:

Try T then set_index

out = df.T.set_index(0).T

CodePudding user response:

Try:

df.set_axis(df.iloc[0], axis=1).drop(0)
  • Related