NumPy ndarray Object, Create ndarray object, ndim: view array dimension, reshape(): change array dimension

NumPy ndarray Object

The ndarray (N-dimensional array) is the fundamental data structure in NumPy. It is a table of elements, all of the same type, indexed by a tuple of positive integers. The dimensions are called axes in NumPy.

Here's a quick tutorial on NumPy ndarrays:

1. Creating an ndarray

An ndarray can be created from a list or tuple using the np.array() function.

import numpy as np # Create a 1D array from a list a = np.array([1, 2, 3]) print("1D array:\n", a) # Create a 2D array from a list of lists b = np.array([[1, 2, 3], [4, 5, 6]]) print("2D array:\n", b) 

2. Inspecting an ndarray

You can inspect the number of dimensions, shape, size, and data type of an ndarray.

print("Number of dimensions of b:", b.ndim) print("Shape of b:", b.shape) print("Size of b:", b.size) print("Data type of b:", b.dtype) 

3. Other ways of creating an ndarray

NumPy provides functions like np.zeros(), np.ones(), np.full(), np.empty(), np.arange(), np.linspace(), etc. to create arrays.

# Create a 2x2 array filled with zeros a = np.zeros((2, 2)) print("Zeros:\n", a) # Create a 2x2 array filled with ones b = np.ones((2, 2)) print("Ones:\n", b) # Create a 2x2 array filled with 7 c = np.full((2, 2), 7) print("Sevens:\n", c) 

4. Accessing elements

Elements in an ndarray can be accessed or modified by indexing.

# Access the element at the 1st row and 2nd column print("Element at (1, 2):", b[1, 2]) # Modify the element at the 1st row and 2nd column b[1, 2] = 5 print("Modified array:\n", b) 

5. Slicing

Slicing can be used to access subarrays.

# Access the first row print("First row:", b[0]) # Access the first column print("First column:", b[:, 0]) # Access a subarray print("Subarray:\n", b[0:2, 1:3]) 

6. Boolean Indexing

Boolean indexing can be used to access elements that satisfy certain conditions.

print("Elements greater than 2:\n", b[b > 2]) 

7. Arithmetic Operations

Arithmetic operations on ndarrays are elementwise.

# Add two arrays c = a + b print("Sum:\n", c) # Multiply two arrays d = a * b print("Product:\n", d) 

These are just some of the basic operations you can perform on ndarrays. NumPy also provides a rich set of functions for linear algebra, statistics, and more.


More Tags

sharepoint-2013 uistoryboardsegue unity-container uigesturerecognizer httpresponse unique-values matlab delphi-xe8 primefaces standard-library

More Programming Guides

Other Guides

More Programming Examples