
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Array Attributes
NumPy Array Attributes
In NumPy, attributes are properties of array objects that provide important information about the arrays and their data. These attributes are used to access various details regarding the structure and configuration of the arrays without modifying them.
In this chapter, we will discuss the various array attributes of NumPy.
NumPy Shape Attribute
The NumPy shape attribute provides the dimensions of the array. It returns a tuple representing the size of the array along each dimension. It can also be used to resize the array.
Example 1
In the following example, we are retrieving the shape of a NumPy array using the shape attribute −
import numpy as np a = np.array([[1,2,3],[4,5,6]]) print (a.shape)
Following is the output obtained −
(2, 3)
Example 2
Here, we are resizing an array using the shape attribute in NumPy −
import numpy as np a = np.array([[1,2,3],[4,5,6]]) a.shape = (3,2) print (a)
This will produce the following result −
[[1, 2] [3, 4] [5, 6]]
Example 3
NumPy also provides a reshape() function to resize an array −
import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = a.reshape(3,2) print (b)
Following is the output of the above code −
[[1, 2] [3, 4] [5, 6]]
NumPy Dimensions Attribute
The ndim attribute returns the number of dimensions (axes) of the array.
In NumPy, the dimension of an array is known as its rank. Each axis in a NumPy array corresponds to a dimension. The number of axes (dimensions) is referred to as the array's rank.
Arrays can be of any dimension, from one-dimensional (1D) arrays (also known as vectors) to multi-dimensional arrays like 2D arrays (matrices) or even higher-dimensional arrays.
Example 1
In this example, we are creating a NumPy array a with "24" evenly spaced integers from "0" to "23" using the arange() function −
import numpy as np a = np.arange(24) print (a)
The output obtained is as shown below −
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Example 2
Here, we are creating a one-dimensional NumPy array a with "24" elements using the arange() function and then reshaping it into a three-dimensional array "b" with the shape provided, resulting in a 3D array −
# This is one dimensional array import numpy as np a = np.arange(24) a.ndim # Now reshape it b = a.reshape(2,4,3) print (b) # b is having three dimensions
After executing the above code, we get the following output −
[[[ 0, 1, 2] [ 3, 4, 5] [ 6, 7, 8] [ 9, 10, 11]] [[12, 13, 14] [15, 16, 17] [18, 19, 20] [21, 22, 23]]]
NumPy Size Attribute
The size attribute returns the total number of elements in the array. In NumPy, the size of an array refers to the total number of elements contained within the array.
- For a one-dimensional array, the size is simply the number of elements.
- For a two-dimensional array, the size is the product of the number of rows and columns.
- For a three-dimensional array, the size is the product of the sizes of all three dimensions.
Example
In the example below, we are using the "size" attribute in NumPy to retrieve the size of a 3D arrray −
import numpy as np # Creating a 3D array array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) print("3D Array:\n", array_3d) print("Size of the array:", array_3d.size)
Following is the output obtained −
3D Array: [[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]] Size of the array: 12
NumPy Data Type Attribute
The dtype attribute describes the data type of the elements in the array. In NumPy, the data type of an array refers to the type of the elements stored in the array.
NumPy supports a wide range of data types, including integers, floats, complex numbers, booleans, and more. Each data type is represented by a dtype object. The "dtype" not only specifies the type of the data but also its size and byte order.
Example
In this example, we are specifying the data type of a NumPy array at the time of its creation using the "dtype" attribute −
import numpy as np # Creating an array of integers int_array = np.array([1, 2, 3], dtype=np.int32) print("Integer Array:", int_array) print("Data type of int_array:", int_array.dtype) # Creating an array of floats float_array = np.array([1.1, 2.2, 3.3], dtype=np.float64) print("Float Array:", float_array) print("Data type of float_array:", float_array.dtype) # Creating an array of complex numbers complex_array = np.array([1 + 2j, 3 + 4j], dtype=np.complex128) print("Complex Array:", complex_array) print("Data type of complex_array:", complex_array.dtype)
This will produce the following result −
Integer Array: [1 2 3] Data type of int_array: int32 Float Array: [1.1 2.2 3.3] Data type of float_array: float64 Complex Array: [1.+2.j 3.+4.j] Data type of complex_array: complex128
NumPy Itemsize Attribute
The itemsize attribute returns the the length of each element of array in bytes.
The item size is determined by the data type (dtype) of the array. Different data types require different amounts of memory. For example, an int32 type requires "4" bytes per element, while a float64 type requires "8" bytes per element.
Example 1
In the following example, we are checking the item size for an array of integer data type "int8" −
# dtype of array is int8 (1 byte) import numpy as np x = np.array([1,2,3,4,5], dtype = np.int8) print (x.itemsize)
We get the output as shown below −
1
Example 2
Now, we are checking the item size for an array of float data type "float32" −
# dtype of array is now float32 (4 bytes) import numpy as np x = np.array([1,2,3,4,5], dtype = np.float32) print (x.itemsize)
The result produced is as follows −
4
NumPy Buffer Information Attribute
The nbytes attribute returns the total number of bytes consumed by the elements of the array.
In NumPy, the buffer information of an array provides details about the underlying memory structure that stores the array data. This includes information on the memory layout, the data type, and the byte offset within the buffer.
Example
In this example, we are using the "nbytes" attribute to retrieve the total memory used by the arrays data buffer −
import numpy as np # Creating an array array = np.array([1, 2, 3, 4, 5], dtype=np.int32) # Checking total memory size of the array print("Total memory size of the array:", array.nbytes, "bytes")
The output obtained is as shown below −
Total memory size of the array: 20 bytes
NumPy Strides Attribute
The strides attribute provides the number of bytes to step in each dimension when traversing an array.
Strides specify the number of bytes that must be skipped in memory to move from one element to the next along each axis. They help in determining how the array is laid out in memory and how to access elements.
Example
In the example below, we are accessing an element in a 2D array using "strides" attribute to calculate the memory address −
import numpy as np # Creating a 2D array array = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Checking the strides print("Array shape:", array.shape) print("Array strides:", array.strides)
The stride for the first axis (rows) is 16 bytes, which means to move from one row to the next, NumPy skips 16 bytes in memory. The stride for the second axis (columns) is 4 bytes, indicating that to move from one column to the next within the same row, NumPy skips 4 bytes −
Array shape: (3, 4) Array strides: (32, 8)
NumPy Flags Attribute
The flags attribute returns information about the memory layout of the array, such as whether it is contiguous in memory.
NumPy provides several flags that describe different aspects of the arrays memory layout and properties −
Sr.No. | Attribute & Description |
---|---|
1 |
C_CONTIGUOUS (C) The data is in a single, C-style contiguous segment |
2 |
F_CONTIGUOUS (F) The data is in a single, Fortran-style contiguous segment |
3 |
OWNDATA (O) The array owns the memory it uses or borrows it from another object |
4 |
WRITEABLE (W) The data area can be written to. Setting this to False locks the data, making it read-only |
5 |
ALIGNED (A) The data and all elements are aligned appropriately for the hardware |
6 |
UPDATEIFCOPY (U) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array |
Example
The following example shows the current values of array's flags −
import numpy as np x = np.array([1,2,3,4,5]) print (x.flags)
Following is the output obtained −
C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False
NumPy Base Attribute
The base attribute returns the base object if the array is a view on another array. If the array owns its data, base is "None". In NumPy, the concept of "array base" refers to the original array from which a new array is derived.
Example
In this example, "view_array" is a view into "original_array", and the base attribute of "view_array" points to "original_array" −
import numpy as np # Creating an array original_array = np.array([[1, 2, 3], [4, 5, 6]]) # Creating a view (a slice) of the original array view_array = original_array[0:1, :] # Checking the base of the view print("Base array of view_array:", view_array.base)
The result produced is as follows −
Base array of view_array: [[1 2 3] [4 5 6]]
NumPy Real and Imaginary Parts Attribute
For arrays with complex numbers, the real and imag attributes return the real and imaginary parts, respectively.
Example
In this example, we are using the "real" attribute to return an array with the real parts and "imag" attribute to return an array with the imaginary parts −
import numpy as np # Creating an array of complex numbers complex_array = np.array([1+2j, 3+4j, 5+6j]) # Accessing the real part real_part = complex_array.real print("Real part:", real_part) # Accessing the imaginary part imaginary_part = complex_array.imag print("Imaginary part:", imaginary_part)
We get the output as shown below −
Real part: [1. 3. 5.] Imaginary part: [2. 4. 6.]
Attributes List
Following is the list of various Array attributes in NumPy −
Sr.No. | Operation & Description |
---|---|
1 |
ndarray.ndim
This attribute returns the number of dimensions in the array. |
2 |
ndarray.shape
This attribute returns the size of the array in each dimension.. |
3 |
ndarray.size
This attribute returns number of elements in the array. |
4 |
ndarray.dtype
This attribute returns the datatype of elements in the array. |
5 |
ndarray.itemsize
This returns the size of each element in the array. |
6 |
ndarray.nbytes
This returns the total bytes consumed by the array elements. |
7 |
ndarray.T
Returns the view of the transposed array. |
8 |
ndarray.real
Returns the real part of the array. |
9 |
ndarray.imag
Returns the imaginary part of the array. |
10 |
ndarray.flat
1D array iterator over the array. |
11 |
ndarray.ctypes
This returns an object to simplify the interaction of the array with the ctypes module. |
12 |
ndarray.data
This returns the buffer containing the actual elements of the array in the memory. |