在 python/pandas 中转置列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19380670/
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
Transpose columns in python/pandas
提问by user2866103
I'm trying to rearrange a dataframe with 5 variables
我正在尝试用 5 个变量重新排列数据框
Data columns (total 7 columns):
Nane 3966 non-null values
Value1 3966 non-null values
Value2 3966 non-null values
Value3 3966 non-null values
Value4 3966 non-null values
Value5 3966 non-null values
Period 3966 non-null values
I'd like period to be the columns, and the other ones as rows.
我希望句点作为列,其他的作为行。
So
所以
Name Value1 .... Value 5 Period becomes
Period 1 period 2 period3 .... period 3966
Name
Value 1
...
Value 5
I've tried using the stack/unstack and the transpose function, but I just can't figure it out. Does anyone have any pointers ?
我试过使用 stack/unstack 和 transpose 函数,但我就是想不通。有没有人有任何指示?
回答by Boud
You want to use the Periodas an index. set_indexwill do this for you. Then you can transpose your resulting table:
您想将Period用作索引。set_index会为你做这件事。然后你可以转置你的结果表:
df.set_index('Period').T
Out[13]:
Period 2010 2011 2012
Name foo bar nil
Value1 0,994369885 0,92930566 0,997754262
Value2 0,780942307 0,274566936 0,488064461
Value3 0,510782105 0,390724018 0,642086396
Value4 0,842522334 0,613705323 0,028703768
Value5 0,383279727 0,287280101 0,764773601

