Lostsoul
Lostsoul

Reputation: 26001

In Pandas can I replace the first row as the header?

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?

Upvotes: 0

Views: 364

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Try:

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

Upvotes: 1

BENY
BENY

Reputation: 323226

Try T then set_index

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

Upvotes: 3

Related Questions