Home > OS >  How to create an array from txt file with numpy.loadtxt with no delimiter
How to create an array from txt file with numpy.loadtxt with no delimiter

Time:12-13

I have a file that it's content is:

30373
25512
65332
33549
35390

So i want to create a 2D (matrix) array of the file content

like this

[[3. 0. 3. 7. 3.]
 [2. 5. 5. 1. 2.]
 [6. 5. 3. 3. 2.]
 [3. 3. 5. 4. 9.]
 [3. 5. 3. 9. 0.]]

So i try this

import numpy as np

print(np.loadtxt('file.txt'))

But this gave me the following

[30373. 25512. 65332. 33549. 35390.]

So it's not the answer that i excepted

And also there is an parameter called delimiter in method

import numpy as np

print(np.loadtxt('file.txt', delimiter=''))

And this was not the excepted answer too

So can any one help me to figure out this problem.

[EDIT]

It's easy to use the following codes

array = [i.split() for i in open('file.txt').read().splitlines()]

But i want to know, is it possible to do this by numpy?

CodePudding user response:

Have you tried np.genfromtxt ?

arr = np.genfromtxt('file.txt', delimiter='')

print(arr)

CodePudding user response:

Simply read ffile using python to list & then typecast to float as follows & then convert to numpy array.

import numpy as np
with open(r"text_file.txt") as f:
  data = [x.rstrip('\n').split(" ") for x in f.readlines() ]
new = []
for x in data:
    for y in x:
        s =list(map(float,str(y)))
        new.append(s)
npa = np.asarray(new, dtype=np.float32)
print(npa)

Gives #

[[3. 0. 3. 7. 3.]
 [2. 5. 5. 1. 2.]
 [6. 5. 3. 3. 2.]
 [3. 3. 5. 4. 9.]
 [3. 5. 3. 9. 0.]]

Note: There could a functional approch. i'm not aware of any functional approches to solve this. so I solved step by step

CodePudding user response:

coniferous was not that far, tho, by replacing loadtxt with genfromtxt, even if that was not just it.

genfromtxt's delimiter option can be either a string describing what separates two fields (eg, ','), or it can also be an integer, which is then the size of the field (for fixed size field format).

So, in your case

np.genfromtxt('file.txt', delimiter=1)

does exactly what you want.

  • Related