1

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?

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

3 Comments

Cheers. Is there a way to iterate through each variable, incrementing by 12 each time for each of the, in this case, 7 climateVarNames?
I'm sorry, I don't understand the question.
For the 12 TMAX columns read them into the numpy array mTx and for the next 12 TMIN columns read them into the mTn numpy array. Iterating through the table using a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.