60

Pretty sure this is very simple.

I am reading a csv file and have the dataframe:

Attribute    A   B   C
a            1   4   7
b            2   5   8
c            3   6   9

I want to do a transpose to get

Attribute    a   b   c
A            1   2   3
B            4   5   6
C            7   8   9

However, when I do df.T, it results in

             0   1   2 
Attribute    a   b   c
A            1   2   3
B            4   5   6
C            7   8   9`

How do I get rid of the indexes on top?

user2237511
  • 1,089
  • 2
  • 13
  • 20
  • 3
    Reset the index and then transpose: `df.reset_index().T`. – Abdou Feb 22 '17 at 02:34
  • Umm...that actually added two rows of 0 1 2. – user2237511 Feb 22 '17 at 02:41
  • 1
    Sorry, I misread the question. If your dataframe is structured in the way you've shown here, `df.T` should get you your desired output. That is, if `df.index` is `Index(['a', 'b', 'c'], dtype='object')` and `df.columns` is `Index(['A', 'B', 'C'], dtype='object')`. – Abdou Feb 22 '17 at 02:45
  • Fyi, I updated my question. I missed the mentioning that the first column has a header of 'Attribute'. df.columns is fine df.index is not, it prints out 0, 1, 2 which makes sense that the transpose then has it. So that's my problem. I read the data from a csv file but I haven't mentioned 0, 1, 2 there. – user2237511 Feb 22 '17 at 02:53
  • 7
    Then `df.set_index('Attribute').T` is what you are looking for. – Abdou Feb 22 '17 at 02:55
  • Yayy!! yes that worked! Thank you! Want to post it as an answer, so I can accept it? I'll update the question to mention I am reading it from a csv. Thank you! – user2237511 Feb 22 '17 at 02:57

3 Answers3

72

You can set the index to your first column (or in general, the column you want to use as as index) in your dataframe first, then transpose the dataframe. For example if the column you want to use as index is 'Attribute', you can do:

df.set_index('Attribute',inplace=True)
df.transpose()

Or

df.set_index('Attribute').T
Samuel Nde
  • 2,565
  • 2
  • 23
  • 23
dimab0
  • 1,062
  • 8
  • 10
15

It works for me:

>>> data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
>>> df = pd.DataFrame(data, index=['a', 'b', 'c'])
>>> df.T
   a  b  c
A  1  2  3
B  4  5  6
C  7  8  9
Tom Lynch
  • 893
  • 6
  • 13
0

If your index column 'Attribute' is really set to index before the transpose, then the top row after the transpose is not the first row, but a title row. if you don't like it, I would first drop the index, then rename them as columns after the transpose.

Sam_Kim
  • 11
  • 1