Shubham Kuse
Shubham Kuse

Reputation: 135

Convert Text file to Array

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!

Upvotes: 2

Views: 3208

Answers (4)

Jonathon McMurray
Jonathon McMurray

Reputation: 2991

>>> 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.]])

Upvotes: 0

damores
damores

Reputation: 2351

If you already have an array by using numpy.array as you mentioned, say in a variable called nums, then you could do the following:

nums = nums.reshape(-1, 4)

Upvotes: 0

jpp
jpp

Reputation: 164813

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.]])

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107347

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.]])

Upvotes: 3

Related Questions