Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading