在python中将单个列转换为2d Matrix

问题描述 投票:-2回答:1

我在单个列中有如下所示的数据,我想将该单个列拆分为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
python-2.7 dataframe
1个回答
0
投票

最简单的方法之一是使用numpy和reshape函数

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表示下一行。假设这是数字数据,您将需要使用上面的代码来获取数字。

© www.soinside.com 2019 - 2024. All rights reserved.