1

i'm working with python/numpy and search in the docs but cant find the method to accomplish this

i have this two arrays and want to concatenate the elements inside the array into a second array

this is my first array

import numpy as np
a = np.array([0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0])

my goal is

Output:

[[00000000], [00000000]]

the reason of this is for later transform every element of the array into hex

crosales
  • 13
  • 1
  • 5

3 Answers3

1
In [100]: a = np.array([[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0]])
In [101]: a
Out[101]: 
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])
In [102]: a.astype(str)
Out[102]: 
array([['0', '0', '0', '0', '0', '0', '0', '0'],
       ['0', '0', '0', '0', '0', '0', '0', '0']], dtype='<U11')
In [103]: a.astype(str).tolist()
Out[103]: 
[['0', '0', '0', '0', '0', '0', '0', '0'],
 ['0', '0', '0', '0', '0', '0', '0', '0']]
In [104]: [''.join(row) for row in _]
Out[104]: ['00000000', '00000000']
hpaulj
  • 175,871
  • 13
  • 170
  • 282
0

You can try this approach:

import numpy as np

a =  np.array([0, 0, 0, 0, 0, 0, 0, 0])

b =  np.array([0, 0, 0, 0, 0, 0, 0, 0])

#concatenate 
concat=np.concatenate((a,b))

#reshape
print(np.reshape(concat,[-1,8]))

output:

[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]]
Aaditya Ura
  • 9,140
  • 4
  • 35
  • 62
  • This is not actually a solution. Print just doesn't show the commas separating the elements of the first axis. – mawall May 20 '20 at 15:37
0

A more concise, pure numpy version, adapted from this answer:

np.apply_along_axis(lambda row: row.astype('|S1').tostring().decode('utf-8'),
                    axis=1,
                    arr=a)

This will create an array of unicode strings with a maximum length of 8:

array(['00000000', '00000000'], dtype='<U8')

Note that this method only works if your original array (a) contains integers in range 0 <= i < 10, since we convert them to single, zero-terminated bytes with .astype('|S1').

mawall
  • 121
  • 1
  • 9