Reputation: 25
I have data as shown below in a single column and i want to split that single column into n number of columns and name rows and columns. How can i do that in python ?
-----------sample data----------
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
------------ The output should look like ---------
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
Upvotes: 0
Views: 1680
Reputation: 1091
One of the easiest ways is to use numpy and the reshape function
import numpy as np
k = np.array(data)
k.reshape([row,column],order='F')
As for your example. You mentioned the data is from a text file so to acquire the data from the text file and reshape
import numpy as np
data = np.genfromtxt("sample-data.txt");
data.reshape([4,7],order='F')
output will be
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]])
I do not know the structure of the data but assuming it is in 1 giant column as seen in the sample above. When importing the data using open
. The following happens.
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']
This results in an array of string values as the \n
means next line. Assuming this is numerical data, you will want to use the code above to get the numbers.
Upvotes: 1