Python 转置熊猫数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24412510/
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 04:34:22  来源:igfitidea点击:

Transpose pandas dataframe

pythonpandasdataframe

提问by pistal

How do I convert a list of lists to a panda dataframe?

如何将列表列表转换为熊猫数据框?

it is not in the form of coloumns but instead in the form of rows.

它不是以列的形式,而是以行的形式。

#!/usr/bin/env python

from random import randrange
import pandas

data = [[[randrange(0,100) for j in range(0, 12)] for y in range(0, 12)] for x in range(0, 5)]
print data
df = pandas.DataFrame(data[0], columns=['B','P','F','I','FP','BP','2','M','3','1','I','L'])
print df

for example:

例如:

data[0][0] == [64, 73, 76, 64, 61, 32, 36, 94, 81, 49, 94, 48]

I want it to be shown as rows and not coloumns.

我希望它显示为行而不是列。

currently it shows somethign like this

目前它显示了这样的东西

     B   P   F   I  FP  BP   2   M   3   1   I   L
0   64  73  76  64  61  32  36  94  81  49  94  48
1   57  58  69  46  34  66  15  24  20  49  25  98
2   99  61  73  69  21  33  78  31  16  11  77  71
3   41   1  55  34  97  64  98   9  42  77  95  41
4   36  50  54  27  74   0   8  59  27  54   6  90
5   74  72  75  30  62  42  90  26  13  49  74   9
6   41  92  11  38  24  48  34  74  50  10  42   9
7   77   9  77  63  23   5  50  66  49   5  66  98
8   90  66  97  16  39  55  38   4  33  52  64   5
9   18  14  62  87  54  38  29  10  66  18  15  86
10  60  89  57  28  18  68  11  29  94  34  37  59
11  78  67  93  18  14  28  64  11  77  79  94  66

I want the rows and coloumns to be switched. Moreover, How do I make it for all 5 main lists?

我想要切换行和列。此外,我如何为所有 5 个主要列表制作它?

This is how I want the output to look like with other coloumns also filled in.

这就是我希望输出与其他列也填充的样子。

     B   P   F   I  FP  BP   2   M   3   1   I   L
0    64 
1    73  
1    76  
2    64  
3    61  
4    32  
5    36  
6    94  
7    81  
8    49  
9    94  
10   48

However. df.transpose()won't help.

然而。df.transpose()不会有帮助。

采纳答案by LFC

import numpy

df = pandas.DataFrame(numpy.asarray(data[x]).T.tolist(),
                      columns=['B','P','F','I','FP','BP','2','M','3','1','I','L'])

回答by pistal

This is what I came up with

这是我想出的

data = [[[randrange(0,100) for j in range(0, 12)] for y in range(0, 12)] for x in range(0, 5)]
print data
df = pandas.DataFrame(data[0], columns=['B','P','F','I','FP','BP','2','M','3','1','I','L'])
print df
df1 = df.transpose()
df1.columns = ['B','P','F','I','FP','BP','2','M','3','1','I','L']
print df1