Understanding how to specify the newshape parameter for numpy reshape ()

I am new to python data analysis and trying to figure out how to manipulate a multidimensional array in another dimension. Online tutorials or forums do not explain how to specify the "newshape" options fornumpy.reshape(a, newshape, order='C')

Here is an example that I am trying to understand. It would be very helpful if someone could explain line 4.

import numpy as np
a1 = np.arrange(8).reshape( (8,1) ) 
b = np.repeat(a1,8,axis=1)
c = b.reshape(2,4,2,4)               # line 4
+4
source share
3 answers

A similar question a week ago: How to understand the ndarray.reshape function?

np.reshape(a, newshape)converted as a.reshape(newshape). But a.reshape- a built-in, compiled method. So the details of how it handles newshapeare hidden (for Python programmers).

, newshape . . .

, , . a[:,1,3] a.__getitem__((slice(None),1,3)). a[(:,1,3)] , ind = (slice(None),1,3); a[ind].

, () :

In [58]: def foo(*args):
    ...:     if len(args)==1:
    ...:         args = args[0]
    ...:     print(args)
    ...:     

In [59]: foo(1,2,3)
(1, 2, 3)

In [60]: foo((1,2,3))
(1, 2, 3)

, :

In [61]: foo(1)
1    
In [62]: foo((1,))
(1,)

def foo(arg):, , .

, , Python . - . , . - , .

===================

reshape numpy/core/src/multiarray/methods.c ( github numpy). c

 def reshape(self, *args, **kwargs):
     n = len(args)
     if n<=1:
         newshape = <parse args[0] in one way>
     else:
         newshape = <parse args in another way>
     return PyArray_Newshape(self, newshape, order)

, :

shape=(2,3)
np.arange(6).reshape(shape)
np.arange(6).reshape(*shape)
np.arange(6).reshape(2,3)
np.arange(6).reshape((2,3))
np.arange(6).reshape((2,)+(3,))
+3

newshape ( - ) numpy.reshape. catch: , numpy.ndarray.reshape (, b.reshape ), newshape. , :

# b = np.random.rand(2*4*2*4)
np.reshape(b,(2,4,2,4))
np.ndarray.reshape(b,(2,4,2,4))
np.ndarray.reshape(b,2,4,2,4)
b.reshape((2,4,2,4))
b.reshape(2,4,2,4)

:

np.reshape(b,2,4,2,4)

, np.reshape np.ndarray.reshape , b.reshape .


help(np.reshape):

reshape(a, newshape, order='C')
    Gives a new shape to an array without changing its data.

help(b.reshape):

a.reshape(shape, order='C')

Returns an array containing the same data with a new shape.

, np.reshape , , -, , . , b.reshape b, order.

+1

shape , , . shape (2, 4, 2, 4) . , , . , c , :

len(c)
# 2

len(c[0])            # same result if you check c[1]
# 4

len(c[0][0])
# 2

len(c[0][0][0])
# 4

. 2D-, :

a = np.array(range(9)) 
a
# array([0, 1, 2, 3, 4, 5, 6, 7, 8])

b = a.reshape(3,3)
b
# array([[0, 1, 2],
#        [3, 4, 5],
#        [6, 7, 8]])

As you can see, it bhas the same data as it adoes, but it has a structure with two dimensions, and each of them has a length of 3, as indicated in the form parameter. And now, if you check:

len(b)
# 3

len(b[0])
# 3

Which returns the form parameter.

0
source

Source: https://habr.com/ru/post/1651973/


All Articles