python - Numpy: vector of indices and value -



python - Numpy: vector of indices and value -

i guess i'm having slow day , can't figure 1 out. have m x n numpy array , want convert vector each element 3 dimensional vector containing row number, column number , value of elements in array.

for example, given numpy array, a, first element in vector be: [1, 1, a[1, 1]] next [1, 2, a[1, 2]] etc.

this sequence produces (3, n*m) array indices , values

in [786]: = np.arange(12).reshape(3,4) in [787]: x=np.vstack([np.indices(a.shape),a[none,...]]).reshape(3,-1) in [788]: x.shape out[788]: (3, 12) in [789]: x out[789]: array([[ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], [ 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])

it can transposed create each 'row' represent element:

in [793]: x.t[0,:] out[793]: array([0, 0, 0]) in [794]: x.t[10,:] out[794]: array([ 2, 2, 10])

it cast structured array length (n*m,), , dtype('i4,i4,i4'). illustration bit messy, job:

in [796]: dt=np.dtype('i4,i4,i4') in [806]: x1=np.zeros(x.shape[1],dtype=dt) in [809]: x1['f0']=x[0] in [810]: x1['f1']=x[1] in [811]: x1['f2']=x[2] # or more compactly: i,n in enumerate(x1.dtype.names): x1[n] = x[i,:] in [812]: x1 out[812]: array([(0, 0, 0), (0, 1, 1), (0, 2, 2), (0, 3, 3), (1, 0, 4), (1, 1, 5), (1, 2, 6), (1, 3, 7), (2, 0, 8), (2, 1, 9), (2, 2, 10), (2, 3, 11)], dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')]) in [813]: x1[10] out[813]: (2, 2, 10) # note, tuple in [814]: x1['f2'] out[814]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

lets original matrix floats, , want preserve type in new array. skipping vstack step:

in [833]: = np.arange(12,dtype=float).reshape(3,4) in [834]: x = np.indices(a.shape).reshape(2,-1) ... in [848]: dt=np.dtype([('row',int), ('col',int), ('value',float)]) in [850]: x1 = np.zeros(x.shape[1], dtype=dt) in [851]: x1['row']=x[0,:] in [852]: x1['col']=x[1,:] in [853]: x1['value']=a.flatten() in [854]: x1 out[854]: array([(0, 0, 0.0), (0, 1, 1.0), (0, 2, 2.0), (0, 3, 3.0), (1, 0, 4.0), (1, 1, 5.0), (1, 2, 6.0), (1, 3, 7.0), (2, 0, 8.0), (2, 1, 9.0), (2, 2, 10.0), (2, 3, 11.0)], dtype=[('row', '<i4'), ('col', '<i4'), ('value', '<f8')]) in [855]: x1[10] out[855]: (2, 2, 10.0)

x1[10] 0d array dtype dt, , shape (), prints tuple.

python numpy

Comments

Popular posts from this blog

java Multi query from Mysql using netbeans -

c# - DotNetZip fails with "stream does not support seek operations" -

c++ - StartServiceCtrlDispatcher don't can access 1063 error -