Home > other >  Convert 2-d numpy array of floats to array of strings by column
Convert 2-d numpy array of floats to array of strings by column

Time:06-01

I have a NumPy array, which is the output of a TensorFlow prediction. The output is looking something like this:

array([[0, 1, 1, ..., 1, 1, 1],
       [0, 1, 1, ..., 1, 1, 1],
       [0, 1, 1, ..., 1, 1, 1],
       ...,
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1]])

for further processing, the 2-d NumPy array should be converted into a 1-d string array (or python list). The output should look something like this:

array(['01111111', '01111111', '01111111', ..., '11111111', '11111111',
       '11111111'], dtype='<U8')

What would be a simple or NumPy best practice way to achieve this?

CodePudding user response:

try this :

import numpy as np

arr = np.array([[0, 1, 1, 1, 1, 1],
       [0, 1, 1, 1, 1, 1],
       [0, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1]])

output = np.array([''.join(map(str, el)) for el in arr], dtype='U8')
print(output)

output:

['011111' '011111' '011111' '111111' '111111' '111111']

CodePudding user response:

You can use apply_along_axis like below:

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


def join_num(r):
    return ''.join(map(str,r))

# or with lamda
# join_num = lambda x: ''.join(map(str,x))



np.apply_along_axis(join_num, 1, a)

Output:

array(['0110111', '0111111', '0110111', '1111111', '1110111', '1111111'],
      dtype='<U7')

CodePudding user response:

Assuming the array is named array and numpy is imported as np, the following line: np.apply_along_axis(''.join, 1, array.astype(str)) will suffice

  • Related