Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

NumPy Ndarray Object

NumPy Ndarray Object

One of the most important features of NumPy is its N-dimensional array object, ndarray, which is a collection of data of the same type, with indexing of elements starting at 0.

The ndarray object is a multidimensional array used to store elements of the same type.

Each element in an ndarray has an area of the same storage size in memory.

The internals of an ndarray consist of the following:

The internal structure of an ndarray:

Strides can be negative, which makes the array move backward in memory, as with obj[::-1] or obj[:,::-1] in slicing.

To create an ndarray, simply call NumPy's array function:

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

Parameter Description:

Name Description
object Array or nested sequence of numbers
dtype The data type of the array elements, optional
copy Whether the object needs to be copied, optional
order The style of creating the array, C for row direction, F for column direction, A for arbitrary direction (default)
subok By default, returns an array consistent with the base class type
ndmin Specify the minimum dimension of the generated array

Example

The following examples help us understand better.

Example 1

import

numpy

as

np

a

=

np

.

array

(

[

1

,

2

,

3

]

)

print

(

a

)

The output is as follows:

[1 2 3]

Example 2

More than one dimension

import

numpy

as

np

a

=

np

.

array

(

[

[

1

,

2

]

,

[

3

,

4

]

]

)

print

(

a

)

The output is as follows:

[[1  2] 
 [3  4]]

Example 3

Minimum dimension

import

numpy

as

np

a

=

np

.

array

(

[

1

,

2

,

3

,

4

,

5

]

,

ndmin

=

2

)

print

(

a

)

The output is as follows:

[[1 2 3 4 5]]

Example 4

dtype parameter

import

numpy

as

np

a

=

np

.

array

(

[

1

,

2

,

3

]

,

dtype

=

complex

)

print

(

a

)

The output is as follows:

[1.+0.j 2.+0.j 3.+0.j]

An ndarray object consists of a contiguous one-dimensional portion of computer memory, combined with an indexing scheme that maps each element to a location in the memory block. The memory block stores elements in row order (C style) or column order (FORTRAN or MatLab style, i.e., the aforementioned F style).