New to python.I have a text file which looks something like this:
1
4
-69
-64
1
5
-57
-56
1
6
-59
-56
1
7
-69
-61
1
8
-53
-53
1
9
-69
-62
1
10
-65
-58
1
11
-69
-58
Want to convert it to a array using numpy which shows output something like this:
[[ 1 4 -69 -64 ]
[ 1 5 -57 -56 ]
[ 1 6 -59 -56 ]
[ 1 7 -69 -61 ]
[ 1 8 -53 -53 ]
[ 1 9 -69 -62 ]
[ 1 10 -65 -58 ]
[ 1 11 -69 -58 ]]
Tried with numpy.array but could'nt get the desired output.
Hopefully, that makes some sense :)
Thanks so much! Any help is greatly appreciated!
Use np.genfromtxt
and split
:
In [5]: arr = np.genfromtxt('test.txt')
In [6]: np.array(np.split(arr, arr.size/4))
Out[6]:
array([[ 1., 4., -69., -64.],
[ 1., 5., -57., -56.],
[ 1., 6., -59., -56.],
[ 1., 7., -69., -61.],
[ 1., 8., -53., -53.],
[ 1., 9., -69., -62.],
[ 1., 10., -65., -58.],
[ 1., 11., -69., -58.]])
Or just use reshape()
at the first place:
In [14]: arr.reshape(arr.size//4, 4)
Out[14]:
array([[ 1., 4., -69., -64.],
[ 1., 5., -57., -56.],
[ 1., 6., -59., -56.],
[ 1., 7., -69., -61.],
[ 1., 8., -53., -53.],
[ 1., 9., -69., -62.],
[ 1., 10., -65., -58.],
[ 1., 11., -69., -58.]])
np.genfromtxt
+ .reshape
is one way:
import numpy as np
arr = np.genfromtxt('txt.csv')
arr.reshape((len(arr)/4, 4))
# array([[ 1., 4., -69., -64.],
# [ 1., 5., -57., -56.],
# [ 1., 6., -59., -56.],
# [ 1., 7., -69., -61.],
# [ 1., 8., -53., -53.],
# [ 1., 9., -69., -62.],
# [ 1., 10., -65., -58.],
# [ 1., 11., -69., -58.]])
如果您已经通过使用numpy.array
拥有一个数组,请在名为nums
的变量中说,那么您可以执行以下操作:
nums = nums.reshape(-1, 4)
>>> np.genfromtxt('so.txt').reshape(-1,4)
array([[ 1., 4., -69., -64.],
[ 1., 5., -57., -56.],
[ 1., 6., -59., -56.],
[ 1., 7., -69., -61.],
[ 1., 8., -53., -53.],
[ 1., 9., -69., -62.],
[ 1., 10., -65., -58.],
[ 1., 11., -69., -58.]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.