-1

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?

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
Duy N
  • 1
  • 3
    `a.reshape(-1,a.shape[-1])`? – Quang Hoang Sep 14 '22 at 05:47
  • Does https://stackoverflow.com/questions/46183967/how-to-reshape-only-last-dimensions-in-numpy help? Alternately: are you familiar with `.reshape`? What is the shape of the example input? What is the shape of the example output? Can you see what the rule is, that tells you how they are related? – Karl Knechtel Sep 14 '22 at 07:10
  • One array has (2,2,3) shape, the other (4,3). Read `np.reshape` docs. – hpaulj Sep 14 '22 at 07:33
  • 1
    Does this answer your question? [How to flatten only some dimensions of a numpy array](https://stackoverflow.com/questions/18757742/how-to-flatten-only-some-dimensions-of-a-numpy-array) – Michael Szczesny Sep 14 '22 at 08:57

3 Answers3

2

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])
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – user11717481 Sep 17 '22 at 20:36
0

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
paime
  • 2,901
  • 1
  • 6
  • 17
0

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])
band
  • 129
  • 7