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, ie [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:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.