Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

How to store a file line by line into numpy.ndarray (Python)

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.

question from:https://stackoverflow.com/questions/66060952/how-to-store-a-file-line-by-line-into-numpy-ndarray-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...