- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Python - Operations on Numpy Arrays

NumPy (Numerical Python) is a powerful library in Python for scientific computing. It provides a high-performance multidimensional array object and tools for working with these arrays. NumPy provides flexible ways to access elements within arrays. You can use indexing and slicing operations to retrieve specific elements or sections of an array.

## Indexing

In NumPy, indexing starts at 0, similar to Python lists. You can access individual elements of an array by specifying their indices within square brackets. For example, given an array arr, you can access the element at index i using arr[i].

## Slicing

NumPy arrays also support slicing, which allows you to retrieve a portion of an array. Slicing is done using the colon (:) operator. The basic syntax for slicing is start:stop:step, where start is the starting index, stop is the ending index (exclusive), and step is the increment between indices.

Examples of slicing operations on NumPy arrays −

arr[2:6] retrieves elements from index 2 to 5 (6 is excluded).

arr[3:] retrieves elements from index 3 to the end of the array.

arr[::2] retrieves elements with a step of 2 (skipping every other element).

arr[::-1] retrieves elements in reverse order.

## Boolean Indexing

NumPy allows you to use Boolean arrays as masks to access elements based on certain conditions. For example, you can create a Boolean array that indicates which elements of an array meet a specific condition, and then use that array as a mask to retrieve the corresponding elements.

### Example

Here's an example of Boolean indexing −

import numpy as np arr = np.array([1, 2, 3, 4, 5]) mask = arr > 2 print(arr[mask])

### Output

[3, 4, 5]

## Integer Array Indexing

NumPy allows you to use arrays of integers as indices to access specific elements. This technique is called integer array indexing. By passing an array of indices, you can retrieve the elements corresponding to those indices.

Example

Here's an example of integer array indexing −

import numpy as np arr = np.array([1, 2, 3, 4, 5]) indices = np.array([0, 2, 4]) print(arr[indices])

### Output

[1, 3, 5]

By mastering these techniques, you can efficiently extract and work with the data you need from NumPy arrays.

## Array Manipulation

### Reshaping Arrays

NumPy allows you to reshape arrays using the reshape() function. Reshaping an array changes its dimensions while maintaining the total number of elements. The reshape() function takes in the desired shape as a tuple and returns a new array with the specified dimensions.

### Example

Here's an example of reshaping an array −

import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) reshaped_arr = arr.reshape((2, 3)) print(reshaped_arr)

### Output

[[1 2 3] [4 5 6]]

In the example above, the original array arr with six elements is reshaped into a 2x3 array reshaped_arr. The reshaped array retains the elements of the original array but arranges them in the specified shape.

You can also use the reshape() function to convert a multi-dimensional array into a one-dimensional array. By specifying the shape as -1, NumPy automatically calculates the appropriate dimension based on the total number of elements.

Example

Here's an example of converting a multi-dimensional array to a one-dimensional array −

import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) reshaped_arr = arr.reshape(-1) print(reshaped_arr)

### Output

[1 2 3 4 5 6]

## Concatenating Arrays

NumPy provides functions like **numpy.concatenate()** and **numpy.stack() **to combine multiple arrays along different axes. Concatenation allows you to join arrays horizontally or vertically, effectively increasing their size or combining them into a larger array.

**numpy.concatenate()**− This function concatenates arrays along an existing axis. By default, it concatenates arrays row-wise (axis 0), but you can specify the**axis**parameter to concatenate along a different axis.

### Example

Here's an example of concatenating arrays using numpy.concatenate() −

import numpy as np arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6]]) concatenated_arr = np.concatenate((arr1, arr2), axis=0) print(concatenated_arr)

### Output

[[1 2] [3 4] [5 6]]

In the example above, **arr1 **and **arr2 **are concatenated along axis 0, resulting in a new array **concatenated_arr.**

**numpy.stack()**− This function stacks arrays along a new axis. It takes a sequence of arrays and the**axis**parameter to specify the new axis along which the arrays will be stacked.

### Example

Here's an example of stacking arrays using numpy.stack() −

import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) stacked_arr = np.stack((arr1, arr2), axis=1) print(stacked_arr)

### Output

[[1 4] [2 5] [3 6]]

In the example above, **arr1 **and **arr2 **are stacked along a new axis (axis 1), resulting in a new array **stacked_arr.**

## Mathematical Operations on Arrays

### Basic Arithmetic Operations

NumPy allows you to perform basic arithmetic operations, such as addition, subtraction, multiplication, and division, on arrays. These operations are performed element-wise, meaning the corresponding elements of the arrays are operated on individually.

### Example

Here are examples of basic arithmetic operations on arrays −

import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) addition = arr1 + arr2 subtraction = arr1 - arr2 multiplication = arr1 * arr2 division = arr1 / arr2 print(addition) print(subtraction) print(multiplication) print(division)

### Output

[5 7 9] [-3 -3 -3] [ 4 10 18] [0.25 0.4 0.5 ]

In the example above, the basic arithmetic operations are applied element-wise to the corresponding elements of **arr1 **and **arr2**, resulting in new arrays addition, subtraction, multiplication, and division.

## Mathematical Functions

NumPy provides a wide range of mathematical functions that can be applied element-wise to arrays. These functions include trigonometric functions, logarithmic functions, exponential functions, and more.

Example

Here are examples of applying mathematical functions to arrays −

import numpy as np arr = np.array([1, 2, 3]) sin_values = np.sin(arr) log_values = np.log(arr) exp_values = np.exp(arr) print(sin_values) print(log_values) print(exp_values)

### Output

[0.84147098 0.90929743 0.14112001] [0. 0.69314718 1.09861229] [ 2.71828183 7.3890561 20.08553692]

In the example above, the np.sin(), np.log(), and np.exp() functions are applied element-wise to the array arr, resulting in new arrays sin_values, log_values, and exp_values.

## Statistical Functions

NumPy provides various statistical functions for computing statistical measures on arrays. These functions include calculating the mean, standard deviation, minimum, maximum, and more.

Example

Here are examples of using statistical functions on arrays −

import numpy as np arr = np.array([1, 2, 3, 4, 5]) mean_value = np.mean(arr) std_value = np.std(arr) min_value = np.min(arr) max_value = np.max(arr) print(mean_value) print(std_value) print(min_value) print(max_value)

### Output

3.0 1.4142135623730951 1 5

In the example above, the np.mean(), np.std(), np.min(), and np.max() functions are used to calculate the mean, standard deviation, minimum, and maximum values of the array arr.

## Conclusion

NumPy arrays are a fundamental data structure for scientific computing in Python. We covered the essentials of working with NumPy arrays, including creating arrays, accessing elements, manipulating their shapes, performing mathematical operations, and comparing arrays.