Home > Software engineering >  How do I flatten a np array by one dimension only?
How do I flatten a np array by one dimension only?

Time:09-14

I have an numpy array

array([[[1, 2, 3],
        [4, 5, 6]],

       [[1, 2, 3],
        [4, 5, 6]]])

and i want

array([[1, 2, 3],
       [4, 5, 6],
       [1, 2, 3],
       [4, 5, 6]])

How do I do that?

CodePudding user response:

ypu want convert 3d array to 2d array. so do this for any 3d array you want:

sh = 3d_array.shape

2d_array = 3d_array.reshape(sh[0]*sh[1], sh[2])

CodePudding user response:

The general formula to flatten a given axis would be:

def flatten_axis(arr, axis):
    """The flatten axis is merged with the axis on its right.
    Such that `res.shape[axis] == (arr.shape[axis] * arr.shape[axis 1])`"""
    if not 0 <= axis <= arr.ndim - 2:
        raise ValueError(
            "Expected `axis` to be between 0 and "
            f"{(arr.ndim-2)=}, but found {axis=}"
        )
    shape = arr.shape
    new_shape = tuple([*shape[:axis], -1, *shape[axis   2 :]])
    return arr.reshape(new_shape)

Which acts as follows:

arr = np.random.randn(3, 5, 7, 11, 13, 15)

print(f"               {arr.shape = }")
for axis in range(arr.ndim - 1):
    print(f"{axis = }  -->  ", end="")
    res = flatten_axis(arr, axis=axis)
    print(f"{res.shape = }")
    assert res.shape[axis] == arr.shape[axis] * arr.shape[axis   1]

Results:

               arr.shape = (3, 5, 7, 11, 13, 15)
axis = 0  -->  res.shape = (15, 7, 11, 13, 15)
axis = 1  -->  res.shape = (3, 35, 11, 13, 15)
axis = 2  -->  res.shape = (3, 5, 77, 13, 15)
axis = 3  -->  res.shape = (3, 5, 7, 143, 15)
axis = 4  -->  res.shape = (3, 5, 7, 11, 195)
axis = 5  -->  ValueError: Expected `axis` to be between 0 and (arr.ndim-2)=4, but found axis=5

CodePudding user response:

Reshape will do. Read this https://numpy.org/doc/stable/reference/generated/numpy.reshape.html

array=np.array([[[1, 2, 3],
    [4, 5, 6]],

   [[1, 2, 3],
    [4, 5, 6]]])

array.reshape(-1,array.shape[2])
  • Related