Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 656
crosales Avatar asked Feb 12 '26 14:02

crosales


2 Answers

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']
like image 156
hpaulj Avatar answered Feb 15 '26 04:02

hpaulj


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

like image 40
mawall Avatar answered Feb 15 '26 02:02

mawall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!