Python 如何在没有索引的情况下转置熊猫中的数据帧?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42381639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:37:52  来源:igfitidea点击:

How do I transpose dataframe in pandas without index?

pythonpandasdataframe

提问by user2237511

Pretty sure this is very simple.

很确定这很简单。

I am reading a csv file and have the dataframe:

我正在读取一个 csv 文件并拥有数据框:

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

但是,当我执行 df.T 时,它会导致

             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?

如何摆脱顶部的索引?

回答by dimab0

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:

您可以首先将索引设置为数据帧中的第一列(或者一般来说,您要用作索引的列),然后转置数据帧。例如,如果要用作索引的列是'Attribute',则可以执行以下操作:

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

Or

或者

df.set_index('Attribute').T

回答by Tom Lynch

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