YouTip LogoYouTip

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 elements of the same type, indexed starting from 0. The `ndarray` object is a multidimensional array used to store elements of the same type. Each element in an `ndarray` occupies the same amount of memory space. The internal structure of an `ndarray` consists of the following: * A pointer to the data (a block of data in memory or a memory-mapped file). * The data type or `dtype`, describing the layout of fixed-size values in the array. * A tuple representing the shape of the array, indicating the size of each dimension. * A tuple of strides, where the integers indicate the number of bytes to "step" in order to move to the next element in the current dimension. Internal structure of an ndarray: !(#) Strides can be negative, which would cause the array to move backwards in memory, as seen in slices like `obj[::-1]` or `obj[:,::-1]`. Creating an `ndarray` is as simple as calling NumPy's `array` function: ```python numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0) **Parameter Description:** | Name | Description | | --- | --- | | object | Array or nested sequence | | dtype | The desired data type for the array elements, optional | | copy | Whether to copy the object, optional | | order | The memory layout of the array: 'C' for row-major (C-style), 'F' for column-major (Fortran or MATLAB-style), 'A' for any (default) | | subok | If True, sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default) | | ndmin | Specifies the minimum number of dimensions the resulting array should have | ### Examples The following examples will help us understand better. ## Example 1 ```python import numpy as np a = np.array([1,2,3]) print(a) The output is as follows: ## Example 2 ```python # More than one dimension import numpy as np a = np.array([[1, 2], [3, 4]]) print(a) The output is as follows: [ ] ## Example 3 ```python # Minimum dimensions import numpy as np a = np.array([1, 2, 3, 4, 5], ndmin = 2) print(a) The output is as follows: [] ## Example 4 ```python # 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] The `ndarray` object is composed of a contiguous one-dimensional part 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-major order (C-style) or column-major order (FORTRAN or MATLAB-style, i.e., the aforementioned F-style).
← Python3 Os PathNumpy Tutorial β†’