[英]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:我必须导入一个文件,例如包含 3 行数字:
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, ie [1,2,3,4]
?如何将它们存储到numpy.ndarray M
中,例如M[0]
给出一个包含第一行的np.array
,即[1,2,3,4]
?
Thanks in advance.提前致谢。
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.])]
Same as Giorgios but with a np.array instead of a list for rows:与 Giorgios 相同,但使用 np.array 而不是行列表:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.