0

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this seems the most natural and simple approach to the problem to me! However, the other answers are also valid and solve the same problem...
1

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

Comments

1

You can use apply_along_axis like below:

Short version:

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

np.apply_along_axis(''.join, 1, a.astype(str))

Explanation version:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.