I know the cvs module provides a very nice way to parse text files in python. I have a file that has the following columns:
x y z b
Here, xyzb are floating point numbers. However, I am faced with the possibility that the order right be permuted in any possible way. For example, it may be that the file comes as
b y x z
Now, I would like to read the data into a numpy array which should store the data in the bxyz format. So, the reading function should be something like:
def read_file(file_path, inputformat='xyzb', delimiter=' '):
Now, I could look at each line and have a big if/else kind of logic where for each of the four positions, I would query the format character and then insert it into the corresponding position in the array. However, I was wondering if there is more elegant way to take care of this permutation?
I would suggest loading the data using numpy.loadtxt
(see documentation ), then array-slicing to correct the column order.
Edit: actually, you can use the usecols
parameter to directly specify the desired column order, like:
import numpy as np
def read_file(file_path, input_format="xyzb", desired_format="bxyz", delimiter=" "):
usecols = [input_format.index(col) for col in desired_format]
with open(file_path, "r") as inf:
return np.loadtxt(inf, usecols=usecols, delimiter=delimiter)
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.