I have a series of csv
files that I am using NumPy's genfromtxt
function to turn into arrays. They each have the following format:
ColA, ColB, ColC
-2, 10, 10
-1, 10, 10
0, 10, 10
1, 10, 10
2, 10, 10
In the case of the above csv
, using genfromtxt(data.csv, delimeter=',', skip_header=1)
will generate an array with shape (5, 3). I can then iterate over each row, ie:
data_array = np.genfromtxt(data.csv, delimeter=',', skip_header=1)
for row in data_array:
some_function(row[0], row[1], row[2])
Where the function in the loop expects and requires three numbers. This breaks down when the csv
only contains one line of data, ie:
ColA, ColB, ColC,
0, -4, 10,
In this case, for row in data_array
will be interpreted as looking at each number in the (1, 3)-shaped array individually, and so I cannot run the function on it. The data I have is a series of csv
files and may or may not have more than one line of data. What is the proper way to handle this so that the some_function(x, y, z)
can always be completed, regardless of the input array? I could do an if
-statement to check if the array is 1D, but it seems like there is a better way to go about this.
您可以使用带有通配符( -1
)的np.reshape
来强制数据为二维数组:
data_array = np.genfromtxt("data.csv", delimiter=',', skip_header=1).reshape(-1,3)
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.