I have data in a text file with 3 columns and 4 rows like this:
5 6.4 17
6 5.8 16
7 5.5 3.9
8 5.3 10.4
I want to read this data from the text file into 3 1D arrays each with 4 elements
I have this code:
import numpy as np with open('data.txt','rt') as filedata: values=np.genfromtxt('data.txt', unpack=True)
this has created a 2D (3,4) array. I managed to split it into 3 subarrays using np.slice(values,4)
but then I didn't know how to rename and subsequently use those subarrays
You can use python's slice notation:
import numpy as np
with open('data.txt','rt') as filedata:
values = np.genfromtxt('data.txt', unpack=True)
array1 = values[:, 0]
array2 = values[:, 1]
array3 = values[:, 2]
When you use slicing the first value defines the range in rows and the second in columns. So by typing values[:, 0]
you say give me all elements in 0th column. The semicolon lets you specify a range. For example, values[0:2, 0]
says give me the first two elements in the 0th column. You can look at the slicing notation in more detail here .
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.