Num py - The Basics

 In NumPy, the main object is the ndarray (n-dimensional array), which represents a homogeneous multidimensional array. These arrays consist of elements, usually numbers, all of the same type, and are indexed by a tuple of non-negative integers. Each dimension in NumPy arrays is referred to as an axis.

For instance, consider the array representing the coordinates of a point in 3D space: [1, 2, 1]. This array has one axis with a length of 3, indicating it contains three elements. In the example below, the array has 2 axes: the first axis has a length of 2, and the second axis has a length of 3.

[[1., 0., 0.], [0., 1., 2.]]

NumPy's array class is called ndarray, often referenced using the alias array. It's important to note that numpy.array is distinct from the array.array class in the Standard Python Library, which only handles one-dimensional arrays and offers fewer functionalities.

The key attributes of an ndarray object are as follows:

  • ndarray.ndim: The number of axes (dimensions) of the array.
  • ndarray.shape: The dimensions of the array, represented as a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m).
  • ndarray.size: The total number of elements in the array, equal to the product of the elements of shape.
  • ndarray.dtype: Describes the type of elements in the array. NumPy provides its own data types like numpy.int32, numpy.int16, and numpy.float64, in addition to standard Python types.
  • ndarray.itemsize: The size in bytes of each element of the array.
  • ndarray.data: The buffer containing the actual elements of the array.

Here's an example illustrating these attributes using NumPy: import numpy as np a = np.arange(15).reshape(3, 5) print(a) print("Shape:", a.shape) print("Number of dimensions:", a.ndim) print("Data type:", a.dtype.name) print("Size of each element (in bytes):", a.itemsize) print("Total number of elements:", a.size) print("Type of array:", type(a)) b = np.array([6, 7, 8]) print(b) print("Type of array b:", type(b))

Comments

Popular posts from this blog

Adding constants to numpy array?