简体   繁体   中英

Concatenate elements of an array with numpy?

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

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']

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]]

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') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM