将单列转换为python中的2d矩阵

时间:2019-03-27 07:17:29

标签: python-2.7 dataframe

我在单列中具有如下所示的数据,我想将该单列拆分为n个列,并命名行和列。我如何在python中做到这一点?

-----------示例数据----------

5
3
5
0
0
1
0
0
18
23
11
1
2
10
1
0
5
6
1
0
1
1
1
0
158
132
150
17

------------输出应类似于---------

     column0 column1 column2 column3 column4 column5 column6
row1    5      0      18      2       5       1       158
row2    3      1      23      10      6       1       132
row3    5      0      11      1       1       1       150
row4    0      0      1       0       0       0       17

1 个答案:

答案 0 :(得分:0)

最简单的方法之一是使用numpy和重塑功能

import numpy as np

k = np.array(data)
k.reshape([row,column],order='F')

以您的示例为例。您提到数据来自文本文件,因此要从文本文件中获取数据并进行整形

import numpy as np

data = np.genfromtxt("sample-data.txt");
data.reshape([4,7],order='F')

输出将为

Out[27]: 
array([[  5,   0,  18,   2,   5,   1, 158],
       [  3,   1,  23,  10,   6,   1, 132],
       [  5,   0,  11,   1,   1,   1, 150],
       [  0,   0,   1,   0,   0,   0,  17]])

我不知道数据的结构,但假设它在1个巨型列中,如上面的示例所示。使用open导入数据时。发生以下情况。

data = open("sample-data.txt",'r').readlines()

data
Out[64]: 
['5\n',
 '3\n',
 '5\n',
 '0\n',
 '0\n',
 '1\n',
 '0\n',
 '0\n',
 '18\n',
 '23\n',
 '11\n',
 '1\n',
 '2\n',
 '10\n',
 '1\n',
 '0\n',
 '5\n',
 '6\n',
 '1\n',
 '0\n',
 '1\n',
 '1\n',
 '1\n',
 '0\n',
 '158\n',
 '132\n',
 '150\n',
 '17']

这将导致字符串值数组,因为\n表示下一行。假设这是数字数据,您将需要使用上面的代码来获取数字。

相关问题