user10229833
user10229833

Reputation:

How to get a numpy array from values of another array (Python)

I have the array

[[ 430  780 1900  420][ 0 0 2272 1704]]

and needs to convert it into this result:

[[[ 430  780 1] [1900  420 1]] [[ 0  0 1] [2272  1704 1]]]

basically turn a 2d array into 3d, separate each array into 2 and append the number 1 to it. How can I achieve it?

Upvotes: 1

Views: 78

Answers (2)

javidcf
javidcf

Reputation: 59731

As pointed out in the comments, the question leaves some ambiguity about what would happen with bigger arrays, but one way to obtain the result that you indicate is this:

import numpy as np

a = np.array([[430, 780, 1900, 420], [0, 0, 2272, 1704]])
b = a.reshape(a.shape[0], -1, 2)
b = np.concatenate([b, np.ones_like(b[..., -1:])], -1)
print(b)
# [[[ 430  780    1]
#   [1900  420    1]]
# 
#  [[   0    0    1]
#   [2272 1704    1]]]

Upvotes: 3

shaik moeed
shaik moeed

Reputation: 5785

Try this, for small size arrays(for large arrays consider @jdehesa answer).

>>> arr = [[ 430, 780, 1900, 420],[ 0, 0, 2272, 1704]]

>>> [[[a[0],a[1],1],[a[2],a[3],1]] for a in arr]

[[[430, 780, 1], [1900, 420, 1]], [[0, 0, 1], [2272, 1704, 1]]]

Upvotes: 1

Related Questions