freak11
freak11

Reputation: 391

Convert a 3D numpy array with strings to a python list in a certain way

Consider the following code:

array = np.array2string(np.arange(27).reshape(3,3,3))

This creates a numpy array with 3D dimension. The output will look like this:

[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]

I want to convert this numpy array to a python list where each index corresponds to a line in the numpy array. It is important to note that there is a whitespace between each number. So the output would look like this:

    Index Type Size  Value 
    0     str    5   0 1 2 
    1     str    5   3 4 5
    2     str    5   6 7 8 
    3     str    5   9 10 11
....
.... and so on

How would I code this?

Upvotes: 0

Views: 149

Answers (1)

Mohammad
Mohammad

Reputation: 3396

You can do this with a sderies of substitutions:

my_array = np.array2string(np.arange(27).reshape(3,3,3))
# remove brackets
my_array = my_array.replace('[', '').replace(']', '').split('\n')
# remove space at the beginning of each line
my_array = [line.lstrip() for line in my_array]
# keep only strings that are not empty
my_array = [line for line in my_array if line]

Result:

['0  1  2',
 '3  4  5',
 '6  7  8',
 '9 10 11',
 '12 13 14',
 '15 16 17',
 '18 19 20',
 '21 22 23',
 '24 25 26']

Upvotes: 1

Related Questions