Reputation: 475
I have a tab delimited table in a text file.
Year TMAX1 TMAX2 TMAX3 TMAX4 TMAX5 TMAX6 TMAX7 TMAX8 TMAX9 TMAX10 TMAX11 TMAX12 TMIN1 TMIN2 TMIN3 TMIN4 TMIN5 TMIN6 TMIN7 TMIN8 TMIN9 TMIN10 TMIN11 TMIN12
1964 29.27419355 28.01724138 26.83870968 21.43333333 17.46774194 14.66666667 13.40322581 15.03225806 16.93333333 18.62903226 23.9 23.40322581 12.0483871
I would like to read each block of data into a numpy array. So far I have this.
import numpy as np
metData = open('metData.txt', "r")
climateVarNames = ['YEAR', 'TMAX', 'TMIN', 'RAIN', 'EVAP', 'RADTN', 'RAINDAYS', 'FROSTDAYS']
a = np.loadtxt(metData, skiprows=1)
for climateVar in climateVarNames:
if "TMAX" == climateVar:
TMAX = 1,2,3,4,5,6,7,8,9,10,11,12
mTx = np.array(a[:,(TMAX)])
if "TMIN" == climateVar:
TMIN = 13,14,15,16,17,18,19,20,21,22,23,24
mTn = np.array(a[:,(TMIN)])
How can I assign the column values to TMAX
, and the rest, automatically? Or is there a better way?
Upvotes: 1
Views: 1135
Reputation: 880399
import numpy as np
a = np.loadtxt('metData.txt', skiprows=1, delimiter='\t')
mTx = a[:, 1:13]
mTn = a[:, 13:25]
Note that if metData.txt
contains more than one line, then a
will be a 2-dimensional array. However, if the data file contains only one line, then a
will be 1-dimensional. In that case, a[:,(1,2,3,4,5,6,7,8,9,10,11,12)]
will raise an IndexError. Thus, the code above assumes the data file contains more than one line.
Upvotes: 1