Skip to content

Instantly share code, notes, and snippets.

@restrepo
Created May 23, 2012 05:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save restrepo/2773380 to your computer and use it in GitHub Desktop.
Save restrepo/2773380 to your computer and use it in GitHub Desktop.
Assigns a dictionary keys to the columns of a numpy array
def dictionarizearray(x,list_of_columns):
"""
Assigns a dictionary key to each of the m-columns
of the (n,m) x array
EXAMPLE in some code which loads this function:
>>> names=['var1','var2',...,'varN']
>>> xnames=dictionarizearray(x,names)
>>> xmask=x[xnames['var1']<xnames['var2']]
#instead of
>>> xmask=x[x[:,0]<x[:,1]]
"""
import numpy as np
import sys
x=np.asarray(x)
if not len(x.shape)==2:
sys.exit('ERROR: Not a two-dimensional array')
if x.shape[1]!=len(list_of_columns):
sys.exit('ERROR: Wrong number of dictionary keys')
dictx={}
for i in range(len(list_of_columns)):
dictx[list_of_columns[i]]=x[:,i]
return dictx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment