technazi
technazi

Reputation: 968

How do I hide the index column in pandas dataframe?

How am I supposed to remove the index column in the first row. I know it is not counted as a column but when I transpose the data frame, it does not allow me to use my headers anymore.

enter image description here

In[297] df = df.transpose()
        print(df)
        df = df.drop('RTM',1)
        df = df.drop('Requirements', 1)
        df = df.drop('Test Summary Report', 1)

        print(df)

This throws me an error "labels ['RTM'] not contained in axis".

RTM is contained in an axis and this works if I do index_col=0

df = xl.parse(sheet_name,header=1, index_col=0, usecols="A:E", nrows=6, index_col=None) 

but then I lose my (0,0) value "Artifact name" as a header. Any help will be appreciated.

Upvotes: 0

Views: 11015

Answers (2)

user3483203
user3483203

Reputation: 51165

Using the setup from @ALollz:

df.set_index('id').rename_axis(None).T

       A   B   C   D   E
val1   1   2   3   4   5
val2  11  12  13  14  15

Upvotes: 2

ALollz
ALollz

Reputation: 59569

You can do this with .iloc, to assign the column names to the first row after transposing. Then you can drop the first row, and clean up the name

import pandas as pd
import numpy as np
df = pd.DataFrame({'id': list('ABCDE'),
                   'val1': np.arange(1,6,1),
                   'val2': np.arange(11,16,1)})
  id  val1  val2
0  A     1    11
1  B     2    12
2  C     3    13
3  D     4    14
4  E     5    15

Transpose and clean up the names

df = df.T
df.columns = df.iloc[0]
df = df.drop(df.iloc[0].index.name)
df.columns.name = None

df is now:

       A   B   C   D   E
val1   1   2   3   4   5
val2  11  12  13  14  15

Alternatively, just create a new DataFrame to begin with, specifying which column you want to be the header column.

header_col = 'id'
cols = [x for x in df.columns if x != header_col]
pd.DataFrame(df[cols].values.T, columns=df[header_col], index=cols)

Output:

id     A   B   C   D   E
val1   1   2   3   4   5
val2  11  12  13  14  15

Upvotes: 2

Related Questions