Alok
Alok

Reputation: 3290

How to auto generate numpy dtype?

I have multiple arrays with array names as

   Level1
   Level2
   Level3
   .
   .

etc. Each array has 4 columsn and any number of rows. Columns names are of the form

 AP%i BP%i AS%i BS%i

where %i corresponds to the corresponding index in the array name (eg Level1 -> AP01 BP01 AS01 BS01). How can I create a dtype of one such array with correct column names where column names are variables?

Upvotes: 0

Views: 611

Answers (1)

nneonneo
nneonneo

Reputation: 179382

You can use something like this to dynamically generate the needed dtypes:

for i in xrange(1, N+1): # N is number of arrays
    arr = globals()['Level%i' % i] # this gets the Level<X> value for each i
    arr.dtype = [('AP%02i' % i,float), ('BP%02i' % i, float), ('AS%02i' % i, float), ('BS%02i' % i, float)]
# example
print Level1[0]['AP01']

Remember to adjust the types in the dtype according to the kind of data you actually have.

Upvotes: 1

Related Questions