1

I have to import a file, which for example contains 3 rows of numbers:

1 2 3 4
1 2 3
1 2 3 4 5 6

How can I store them into a numpy.ndarray M, so that for example M[0] gives a np.array containing the first row, i.e. [1,2,3,4]?

Thanks in advance.

2 Answers 2

3

How about this:

import numpy as np


with open('test_file.txt') as file:
    arr = np.array(
        [
            np.array([float(num) for num in line.strip().split("\t")])
            for line in file
        ]
    )
print(arr)

and the array should look like the one below:

[array([1., 2., 3., 4.]) array([1., 2., 3.])
 array([1., 2., 3., 4., 5., 6.])]
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, but i would have an array instead of a list, for each row.
@Wil Oh I missed that. Please see the updated answer
Thank you @Giorgos. Since my row is '13.8\t21.6\t28.9\t34.3\t38.2\t42\t44.6\t46.3\t47.4\t48.2\t47.4\t45.5\t\n', I put '\t' instead of " " in split(). But it gives me ValueError: could not convert string to float: ''. How can I fix it? Thanks.
@Wil Looks like there are whitespaces? See my updated answer again
0

Same as Giorgios but with a np.array instead of a list for rows :

import numpy as np


with open('test_file.txt') as file:
    arr = np.array(
        [
            np.array([float(num) for num in line.split(" ")])
            for line in file
        ]
    )
print(arr)

2 Comments

I would rather make a comment under Giorgios post, I feel like your post isn't sufficiently different to actually constitute answer on its own.
I agree but it seems below "50 reputations" we are not able to post a comment under others answers than ours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.