Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas index title in line with column headers

For my dataset I want to replace the automatic index with the first column in the dataframe and set the new index title inline with all the column names of the dataframe.

Original dataset:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]]),columns=['a','b','c'])
df

  a b c 
0 1 2 3
1 4 5 6

Set the index as the first column:

df.set_index('a',inplace=True)
df

  b c
a 
1 2 3
4 5 6

However, now I am stuck on how to get the index title inline with the column headers. Below is the output I am looking for:

a b c
1 2 3
4 5 6
like image 349
Ariel Avatar asked Apr 26 '17 13:04

Ariel


People also ask

How do I make a row a value in a column header in Python?

columns() to Convert Row to Column Header. You can use df. columns=df. iloc[0] to set the column labels by extracting the first row.

How do I add a title row in pandas?

Creating a data frame from CSV file and creating row header While reading the data and storing it in a data frame, or creating a fresh data frame , column names can be specified by using the names attribute of the read_csv() method in Python.


2 Answers

Use this trick, but I think it is not best practice:

df.columns.name = df.index.name
df.index.name = None
print (df)
a  b  c
1  2  3
4  5  6
like image 55
jezrael Avatar answered Sep 20 '22 09:09

jezrael


You can use

print(df.reset_index().to_string(index=False))

For example

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]]),columns=['a','b','c'])
df.set_index('a', inplace=True)
df

   b  c
a      
1  2  3
4  5  6

print(df.reset_index().to_string(index=False))
 a  b  c
 1  2  3
 4  5  6
like image 21
Kamaraju Kusumanchi Avatar answered Sep 24 '22 09:09

Kamaraju Kusumanchi