Denzyl
Denzyl

Reputation: 176

How to set column headers to the first row in Pandas dataframe?

How do I set the column header of a dataframe to the first row of a dataframe and reset the column names?

# Creation of dataframe

df = pd.DataFrame({"A": ["1", "4", "7"],
                   "B": ["2", "5", "8"],
                   "C": ['3','6','9']})

# df:

   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9

Desired Outcome:

   0  1  2
0  A  B  C
1  1  2  3
2  4  5  6
3  7  8  9

Upvotes: 2

Views: 6124

Answers (3)

mozway
mozway

Reputation: 260640

What you want to do is similar to reset_index but on the other axis. Unfortunately, there is no axis parameter in reset_index.

But, you can cheat a bit and apply a double transposition to handle the columns as index temporarily:

df.T.reset_index().T.reset_index(drop=True)

output:

   0  1  2
0  A  B  C
1  1  2  3
2  4  5  6
3  7  8  9

Upvotes: 3

user7864386
user7864386

Reputation:

You can use np.vstack on a list of column names and the DataFrame to create an array with one extra row; then cast it into pd.DataFrame:

out = pd.DataFrame(np.vstack([df.columns, df]))

Output:

   0  1  2
0  A  B  C
1  1  2  3
2  4  5  6
3  7  8  9

Upvotes: 0

jezrael
jezrael

Reputation: 862661

Use concat with Index.to_frame with transpose for one row DataFrame and last set columns names by range:

df = pd.concat([df.columns.to_frame().T, df], ignore_index=True)
df.columns = range(len(df.columns))
print (df)
   0  1  2
0  A  B  C
1  1  2  3
2  4  5  6
3  7  8  9

Or use DataFrame.set_axis for chained method solution:

df = (pd.concat([df.columns.to_frame().T, df], ignore_index=True)
        .set_axis(range(len(df.columns)), axis=1))

Upvotes: 4

Related Questions