Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging numpy array elements using join() in python

Tags:

python

Want to convert the following numpy array a

    a =  [
    array([['x', 'y', 'k'], ['d', '2', 'z'], ['a', '15', 'r']], dtype='|S2'), 
    array([['p', '49'], ['l', 'n']], dtype='|S2'), 
    array([['5', 'y'], ['33', 'u'], ['v', 'z']], dtype='|S2'), 
    array([['f', 'i'], ['c', 'm'], ['u', '98']] dtype='|S2')
    ]

into output b

  b =  x!y.d!2.a!15 * x!k.d!z.a!r , p!49.l!n , 5!y.33!u.v!z , f!i.c!m.u!98

Consider each sub-array like this

   #x  #y  #k
   #d  #2  #z
   #a  #15 #r 

Then merge 0 and 1 columns with '!' and each row with '.' Then merge 0 and 2 column. And so on. Here 0,1 and 0,2 columns are merged using '*' And ',' is used to merge the sub-arrays

Just merging the strings using '!' '.' '*' ','

I tried the following code. Couldnt get the result though

temp = []
for c in a:
    temp = a[0:]
    b =  " * ".join(".".join(var1+"!"+var2 for var1,var2 in zip(temp,a) for row in a)
    print b
print " , "
like image 827
Chloe Avatar asked Nov 24 '15 04:11

Chloe


1 Answers

In [144]: " , ".join(" * ".join(".".join(str(xx) + '!' + str(yy) for xx, yy in zip(x[:, 0], x[:, _x])) for _x in range(1, len(x[0]))) for x in a)
Out[144]: 'x!y.d!2.a!15 * x!k.d!z.a!r , p!49.l!n , 5!y.33!u.v!z , f!i.c!m.u!98'
like image 166
namit Avatar answered Sep 20 '22 23:09

namit