0

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.

2
  • Do you want the first column to become the column headers after transposing? Commented Aug 13, 2018 at 21:15
  • Yes sir! That is exactly what I want. Commented Aug 13, 2018 at 21:17

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

df.iloc[0]! I almost searched how to address a cell in da ataframe but did not execute it. Thanks a lot. Do you know how can i not lose my header for column 0 which is 'Artifact Name'
2

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

4 Comments

Thanks! This works like a charm. Do you know how can I not lose my 'id' label?
If you want to keep id, just use df.set_index('id').T
Yes! I did that and it shows it in the console but when I write it to an excel file using xlsxwrite I lose the value of it.
I figured what i was doing wrong was df = df.T. :/ Sorry for the silly questions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.