how to do the mapping btw numpy arrayvalues and matrix columns

devnew at gmail.com devnew at gmail.com
Sun Nov 4 18:22:18 CET 2007


CW,
thanx for the reply..but i was looking for a mapping BTW each item of
a numpy.ndarray and the corresponding column of a numpy.matrix ,after
some struggle :-) i came up with this

#a function to return a column from a matrix
def getcol(data, colindex):
    return data[:,colindex]    #returns a matrix obj

#function to set a column of a matrix with a given matrix
def setcol(data, inmat,colindex):
    data[:,colindex]=inmat  #both data and inmat are matrix objs

#now i have an ndarray with 5 elements
evalarray=array(([11.0,33.0,22.0,55.0,44.0]))

#and a matrix with 5 columns
evectmat=matrix(([1.3,2.5,3.2,6.7,3.1],
                  [9.7,5.6,4.8,2.5,2.2],
                  [5.1,3.7,9.6,3.1,6.7],
                  [5.6,3.3,1.5,2.4,8.5]

           ))

the first column of evectmat corresponds to first element of evalarray
and so on..
then i did this

mydict=dict(
[(evalarray[x],getcol(evectmat,x)) for x in range(len(evalarray))]
)
klst=mydict.keys()

klst.sort()
klst.reverse() #because i want the largest value as first

newevectmat=matrix(zeros((4,5)))

for x in range(len(klst)):
    newcol=mydict[klst[x]]
    setcol(newevectmat,newcol,x)

print "newevectmat:"
print newevectmat

this gives me the desired result..now i have a new matrix with columns
arranged corresponding to the values of evalarray

i don't know if this is a good way(or even pythonish ) to do it..i am
a beginner afterall.!. any suggestions most welcome
TIA
dn










>
> from numpy import matrix, asarray
> obj = matrix(([1.3,2.5,3.2,6.7,3.1],
>                [9.7,5.6,4.8,2.5,2.2],
>                [5.1,3.7,9.6,3.1,6.7],
>                [5.6,3.3,1.5,2.4,8.5]))
> ar = asarray(obj)
> val_to_col_list = []
> for row in ar:
>      for ind,val in enumerate(row):
>          val_to_col_list.append((val,ind))
> val_to_col_list.sort()
>
> If instead you require a map, such that each value maps to a list of the
> columns it appears in, you could try the following:
>
> val_col_map = {}
> for row in ar:
>      for col,val in enumerate(row):
>          tmplist=val_col_map.get(val,[])
>          tmplist.append(col)
>          val_col_map[val]=tmplist
> val_keys = val_col_map.keys()
> val_keys.sort()
>
> val_keys is now a sorted list of unique values from your original
> matrix.  Use these values as keys for val_col_map.
>
> Eww... but it works.  You'll want to be really careful with floating
> point numbers as keys, seehttp://docs.python.org/tut/node16.htmlfor
> more details.
>
> Best of luck,
>
> Cameron.





More information about the Python-list mailing list