Skip to content Skip to sidebar Skip to footer

Python - Create An Array From Columns In File

I have a text file with two columns and n rows. Usually I work with two separate vector using x,y=np.loadtxt('data',usecols=(0,1),unpack=True) but I would like to have them as an a

Solution 1:

I think you simply need to not unpack the array you get back from loadtxt. Do:

arr = np.loadtxt('data', usecols=(0,1))

If your file contained:

0 1
2 3
4 5

arr will be like:

[[0, 1],
 [2, 3],
 [4, 5]]

Note that to index into this array, you need to specify the row first (and indexes start at 0):

arr[1,0] == 2 # True!

You can find the x values that correspond to a give y value with:

x_vals = arr[:,0][arr[:,1]==y_val]

The indexing will return an array, though x_vals will have only a single value if the y_val was unique. If you know in advance there will be only one match for the y_val, you could tack on [0] to the end of the indexing, so you get the first result.

Post a Comment for "Python - Create An Array From Columns In File"