Open In App

25+ Most Useful NumPy Snippets

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

NumPy is an open-source library necessary for scientific computing in Python. It supports large multi-dimensional arrays and matrices along with high-level mathematical functions to perform any operation on those arrays. At its core, the `ndarray` object defines how data needs to be stored and manipulated, enabling that with greater efficiency and performance than traditional Python lists.

25-Most-Useful-Numpy-Snippets

In this article, we will discuss about the numpy Snippets in detail:

What is Numpy?

NumPy stands for Numerical Python and it is a core library in Python. It is specifically designed to perform numerical computations efficiently, support large multi-dimensional arrays and matrices, along with many mathematical functions to execute various operations on these data structures.

Due to the efficient speed and usage of memory, NumPy is quickly gaining popularity and adapting numerous applications in the domain of scientific computing, data analysis and machine learning. It provides broadcasting for element-wise operations, advanced linear algebra utilities, random number generation and tight integration with other Python libraries such as Pandas, Matplotlib, and TensorFlow. NumPy is built on C, so it's guaranteed to be fast and making it a go-to for numerical processing.

25+ Most Useful Numpy Snippets

Array Creation

NumPy offers many ways of creating arrays that are the building blocks for effective numerical computation in Python. The following are the methods for creating 1D and 2D arrays along with specific functions such as 'arange()', 'linspace()', 'zeros()' and 'ones()'.

1. One-Dimensional Arrays

To create a one-dimensional array, use the 'np.array()' function by supplying a list or a tuple.

Python
import numpy as np

# Creating a 1D array from a list
arr_1d = np.array([1, 2, 3, 4, 5])
print(arr_1d)

2. Two- dimensional Arrays

2D arrays, or two-dimensional arrays can be created by passing a list of lists (or tuples) to the 'np.array()' function.

Python
# Creating a 2D array from a list of lists
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)

3. Built-in Functions for Array Creation

NumPy offers several built-in functions to create arrays with specific properties:

a. np.zeros(shape)

Creates an array filled with zeros.

Python
# Creating a 2D array filled with zeros
zeros_array = np.zeros((2, 3))
print(zeros_array)

b. np.ones(shape)

Creates an array filled with ones.

Python
# Creating a 2D array filled with ones
ones_array = np.ones((3, 3))
print(ones_array)

c. np.full(shape, fill_value)

Creates an array filled with a specified value.

Python
# Creating a 2D array filled with the value 7
full_array = np.full((2, 2), 7)
print(full_array)

d. np.arange(start, stop, step)

Creates an array with evenly spaced values within a specified range.

Python
# Creating an array from 0 to 9
range_array = np.arange(0, 10)
print(range_array)

e. np.linspace(start, stop, num)

Creates an array with evenly spaced values over a specified interval.

Python
# Creating an array with 5 values evenly spaced between 0 and 1
linspace_array = np.linspace(0, 1, 5)
print(linspace_array)

Array Attributes in NumPy

NumPy arrays have many useful attributes describing its structure and features. A clear understanding of the attributes would make data handling in arrays possible effectively. Now, let us find out about the major attributes on array properties below:

4. Shape of an Array

The shape attribute returns a tuple representing the size of the array in each dimension. For example, for a 2D array, it will return a tuple indicating the number of rows and columns.

Python
import numpy as np

# Creating a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) 

5. Understanding Data Types ('dtype')

The dtype attribute describes the data type of the elements in the array. NumPy supports various data types including integers, floats and more complex types.

Python
# Checking the data type of elements
print(arr.dtype)  

6. Accessing Size and Dimensions

a. Size

The size attribute returns the total number of elements in the array, regardless of its shape.

Python
# Getting the total number of elements
print(arr.size)  

b. Number of Dimensions

The ndim attribute indicates the number of dimensions (axes) in the array.

Python
# Checking the number of dimensions
print(arr.ndim)  

Indexing and Slicing in NumPy

Indexing and slicing are two commonly used techniques applied when working with elements inside the arrays in NumPy. The chapter mentions basic indexing techniques, more complex methods of slicing and boolean indexing for data filtering.

7. Basic Indexing Techniques

Indexing can access elements within an array in NumPy by using their index values which are zero-based. Any element from both 1D and multi-dimensional arrays can be accessed using their index values.

Python
import numpy as np

# Creating a 1D array
arr_1d = np.array([10, 20, 30, 40, 50])

# Accessing elements
print(arr_1d[0])  # Output: 10 (first element)
print(arr_1d[3])  # Output: 40 (fourth element)

# Creating a 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Accessing elements in a 2D array
print(arr_2d[0, 1]) 
print(arr_2d[1, 2])  

8. Advanced Slicing Techniques

Slicing lets you get a subarray of an array. You can use the colon operator (`:`) to specify start and end indices.

Python
# Slicing a 1D array
print(arr_1d[1:4])  

# Slicing a 2D array
print(arr_2d[:, 1])   
print(arr_2d[0, :])  

9. Boolean Indexing for Filtering Data

Boolean indexing filter elements based on conditions. You create a boolean array that represents whether each element meets a specific condition.

Python
# Slicing a 1D array
print(arr_1d[1:4])  

# Slicing a 2D array
print(arr_2d[:, 1])   
print(arr_2d[0, :])   

Manipulating Arrays in NumPy

NumPy offers several array manipulation functions. These functions can make data handling as well as its transformation much faster. Below are some key operations including reshaping, flattening, concatenating, splitting and modifying the elements of the array.

10. Reshaping and Flattening Arrays

a. Reshaping Array

This function reshapes an array and returns a new view of the array without changing any data. Its use is always there when your data needs a different dimensional form.

Python
import numpy as np

# Create a 1D array
array1 = np.array([1, 3, 5, 7, 9, 11])

# Reshape the 1D array into a 2D array (2 rows and 3 columns)
array2 = np.reshape(array1, (2, 3))
print(\"Original array:\
\", array1)
print("\
Reshaped array:\", array2)

b. Flattening Arrays

The flatten() method returns a copy of the array collapsed into one dimension. Alternatively, ravel() returns a flattened array but does not necessarily create a copy.

Python
# Flattening the reshaped array
flattened_array = array2.flatten()
print("Flattened array:", flattened_array)

11. Concatenating and Splitting Arrays

a. Concatenating Arrays

You can concatenate multiple arrays using 'np.concatenate()', 'np.vstack()' for vertical stacking, and 'np.hstack()' for horizontal stacking.

Python
# Create two arrays to concatenate
array3 = np.array([[1, 2], [3, 4]])
array4 = np.array([[5, 6], [7, 8]])

# Concatenate arrays vertically
vertical_concat = np.vstack((array3, array4))
print("\nVertically concatenated array:\n", vertical_concat)

# Concatenate arrays horizontally
horizontal_concat = np.hstack((array3, array4))
print("\nHorizontally concatenated array:\n", horizontal_concat)

b. Splitting Arrays

You can split an array into multiple sub-arrays using `np.split()`, `np.hsplit()`, or `np.vsplit()`.

Python
# Splitting an array into two sub-arrays
split_arrays = np.split(vertical_concat, 2)
print("Split arrays:", split_arrays)

12. Modifying Array Elements

You can modify elements in an array by directly accessing them using indexing.

Python
# Modifying elements in the original array
array1[0] = 100
print("\nModified original array:\n", array1)

# Modifying specific elements in a 2D array
array2[0, 1] = 200
print("\nModified reshaped array:\n", array2)

Math Operations in NumPy

A robust framework has NumPy offered for mathematical operation on arrays very efficient for straightforward computations. The key aspect, therefore, discussed below is to do with element-wise operations, universal functions and the aggregate functions.

13. Element-Wise Arithmetic Operations

NumPy supports element-wise arithmetic operations on arrays. This means corresponding elements from two arrays are operated together. The arithmetic operations supported are addition, subtraction, multiplication, division, and exponentiation.

Python
import numpy as np

# Creating two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Element-wise addition
addition_result = a + b
print("Addition:", addition_result)  

# Element-wise subtraction
subtraction_result = a - b
print("Subtraction:", subtraction_result)  
# Element-wise multiplication
multiplication_result = a * b
print("Multiplication:", multiplication_result) 
# Element-wise division
division_result = a / b
print("Division:", division_result)  

# Element-wise power operation
power_result = a ** b
print("Power:", power_result) 

14. Universal Functions (ufuncs)

Universal functions (ufuncs) in NumPy are functions that perform operations element-wise on arrays. They help to compute mathematical operations efficiently.

Some commonly used ufuncs are:

  • np.add(): It performs element-wise addition.
  • np.subtract(): It performs element-wise subtraction.
  • np.multiply(): It performs element-wise multiplication.
  • np.divide(): It performs element-wise division.
  • np.power(): Element-wise exponentiation.
  • np.mod(): Element-wise modulus operation.
Python
# Using ufuncs for element-wise operations
add_result = np.add(a, b)
print("Ufunc Addition:", add_result)

multiply_result = np.multiply(a, b)
print("Ufunc Multiplication:", multiply_result) 

15. Aggregate Functions

Aggregate functions in NumPy perform operations that summarize or aggregate data across an array. Common aggregate functions include `mean()`, `sum()`, `min()`, `max()`, and `std()` (standard deviation).

Python
# Creating a multi-dimensional array
arr = np.array([[1, 2, 3], [4, 5, 6]])

# Calculating the sum of all elements
total_sum = np.sum(arr)
print("Total Sum:", total_sum)  

# Calculating the mean of all elements
mean_value = np.mean(arr)
print("Mean Value:", mean_value)  

# Calculating the standard deviation
std_dev = np.std(arr)
print("Standard Deviation:", std_dev)  

# Summing along specific axes
sum_axis0 = np.sum(arr, axis=0)  # Sum along columns
print("Sum along axis 0 (columns):", sum_axis0) 

sum_axis1 = np.sum(arr, axis=1)  # Sum along rows
print("Sum along axis 1 (rows):", sum_axis1)  

Linear Algebra Operations in NumPy

NumPy contains an exhaustive number of functions to accomplish the most significant linear algebra operations that find widespread usage in applications like data science, machine learning, and scientific computing. A few key ones are shown next-matrix multiplication, calculation of determinants and inverses of matrices, and solution to a linear system of equations.

16. Matrix Multiplication

Matrix multiplication can be performed using the `@` operator or the `np.dot()` function. The `@` operator is preferred for its readability.

Python
import numpy as np

# Creating two matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Matrix multiplication using @ operator
C = A @ B
print("Matrix Multiplication (A @ B):\n", C)

# Alternatively using np.dot()
D = np.dot(A, B)
print("Matrix Multiplication (np.dot()):\n", D)

17. Determinants and Inverses of Matrices

You can calculate the determinant of a matrix using 'np.linalg.det()' and the inverse using 'np.linalg.inv()'.

Note: The determinant must be non-zero for the inverse to exist. If the determinant is zero, the matrix is singular and does not have an inverse.

Python
# Creating a square matrix
matrix = np.array([[4, 2], [3, 1]])

# Calculating the determinant
determinant = np.linalg.det(matrix)
print("Determinant:", determinant)

# Calculating the inverse
inverse_matrix = np.linalg.inv(matrix)
print("Inverse Matrix:\n", inverse_matrix)

18. Solution for Linear Equations

The solution to a system of linear equations given in matrix form $ Ax = b $ can be obtained using 'np.linalg.solve()'. It computes the solution $ x $ for the equation $ Ax = b $.

Python
# Coefficient matrix A
A = np.array([[3, 2], [1, 2]])

# Constant matrix b
b = np.array([5, 5])

# Solving for x in Ax = b
solution = np.linalg.solve(A, b)
print("Solution to the linear equations:\n", solution)

Statistical Functions in NumPy

NumPy has a range of statistical functions, which are quite important for any data analysis, enabling users to compute the key statistical measures like mean, median, variance, correlation, and covariance. The functions are optimized for performance and can work with one-dimensional and multi-dimensional arrays.

19. Computing Statistical Measures

  • Mean: The mean is a value calculated using 'np.mean()'. It adds together all of the elements in the array and divides by how many number elements are in the array.
  • Median: The median is the middle value, determined using 'np.median()' to find the middle number in a sorted list of data.
  • Variance: Variance calculates the amount of scatter the numbers will have from their mean. It can be determined using 'np.var()'.
  • Standard Deviation: Standard deviation is the square root of variance and can be calculated using 'np.std()'.
Python
import numpy as np

# Creating an array of data
data = np.array([1, 2, 3, 4, 5, 6])

# Calculating mean
mean_value = np.mean(data)
print("Mean:", mean_value)  

# Calculating median
median_value = np.median(data)
print("Median:", median_value) 

# Calculating variance
variance_value = np.var(data)
print("Variance:", variance_value) 

# Calculating standard deviation
std_dev_value = np.std(data)
print("Standard Deviation:", std_dev_value)  

20. Correlation and Covariance Calculations

a. Correlation

Correlation measures the strength and direction of a linear relationship between two variables. NumPy provides 'np.corrcoef()' to compute the correlation coefficient matrix.

b. Covariance

Covariance indicates the direction of the linear relationship between two variables. It can be calculated using 'np.cov()''.

Python
# Creating two arrays for correlation and covariance
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])

# Calculating correlation coefficient matrix
correlation_matrix = np.corrcoef(x, y)
print("Correlation Coefficient Matrix:\n", correlation_matrix)

# Calculating covariance matrix
covariance_matrix = np.cov(x, y)
print("Covariance Matrix:\n", covariance_matrix)

Input/output Operations with NumPy

NumPy provides comprehensive input/output (I/O) functions to read in data from files and save arrays to external files. Such functionality is necessary for any kind of data analysis since one needs to import datasets, then export processed data.

21. Read-in Data from Files: An Example of CSV

a. For CSV files

To read data from files, particularly CSV (Comma-Separated Values) files, NumPy offers `np.loadtxt()` to load numeric data and `np.genfromtxt()` for more complex data with missing values.

Python
import numpy as np

# Assuming 'data.csv' contains numeric data
data = np.loadtxt('data.csv', delimiter=',')
print("Data loaded from CSV:\n", data)

b. For structured data

To read structured data or in cases with missing values, use 'np.genfromtxt()'

Python
# Loading structured data from a CSV file
structured_data = np.genfromtxt('data.csv', delimiter=',', names=True)
print("Structured Data:\n", structured_data)

22. Saving Arrays to Files

To save NumPy arrays to files, you can use several functions depending on the desired file format:

a. Binary Format

Use 'np.save()' to save an array in binary format which is efficient for storage and retrieval.

Python
# Creating an array
array_to_save = np.array([[1, 2], [3, 4]])

# Saving the array to a binary file
np.save('array.npy', array_to_save)

b. Text Format: Use 'np.savetxt()' to save an array in a text file.

Python
# Saving the array to a text file
np.savetxt('array.txt', array_to_save, delimiter=',')

23. Loading Saved Arrays

You can load saved arrays back into your program using 'np.load()' for binary files and 'np.loadtxt()' for text files.

Python
# Loading the saved binary array
loaded_array = np.load('array.npy')
print("Loaded Array from Binary File:\n", loaded_array)

# Loading the saved text array
loaded_text_array = np.loadtxt('array.txt', delimiter=',')
print("Loaded Array from Text File:\n", loaded_text_array)

Extended Features in NumPy

NumPy aside from the above features that advance its role in numerical computations includes the following advanced features: broadcasting rules, capabilities in generating random numbers and working with structured and record arrays.

24. Broadcasting Rules for Performing Operations on Arrays of Different Shapes

This is a very powerful mechanism in NumPy to perform arithmetic operations between arrays of different shapes.

Python
import numpy as np

# Creating a 1D array and a 2D array
array1 = np.array([1, 2, 3])        
array2 = np.array([[10], [20], [30]])  

# Broadcasting operation
result = array1 + array2
print("Broadcasting Result:\n", result)

25. Random Number Generation Capabilities

NumPy contains a comprehensive module called 'numpy.random' which can be used to generate lots of random numbers. These range from random integers and floats to sampling from various distributions.

Python
# Importing the random module
import numpy as np

# Generating random floats between 0 and 1
random_floats = np.random.rand(3, 2)  
print("Random Floats:\n", random_floats)

# Generating random integers between a specified range
random_integers = np.random.randint(0, 10, size=(4,))
print("Random Integers:\n", random_integers)

# Generating samples from a normal distribution
normal_samples = np.random.normal(loc=0.0, scale=1.0, size=(5,))
print("Normal Distribution Samples:\n", normal_samples)

26. Working with Structured Arrays and Record Arrays

Structured arrays allow you to create arrays that contain fields of different data types. This is particularly useful for representing complex data records.

Python
# Defining a structured data type
dtype = np.dtype([('name', 'U10'), ('age', 'i4'), ('height', 'f4')])

# Creating a structured array
structured_array = np.array([('Alice', 25, 5.5), ('Bob', 30, 6.0)], dtype=dtype)
print("Structured Array:\n", structured_array)

# Accessing fields in structured arrays
print("Names:", structured_array['name'])
print("Ages:", structured_array['age'])

Integrating with other Libraries

The integration of NumPy with other libraries like Pandas, Matplotlib, and SciPy adds significantly more data manipulation and visualization capabilities along with scientific computing to Python. Here is a very brief description of how it all works together.

27. Using NumPy with Pandas for Data Manipulation

Pandas is built on top of NumPy and uses its powerful array structures to handle and manipulate data efficiently. With Pandas, you can perform complex data operations such as cleaning, transforming, and analyzing datasets.

  • Data Structures: Pandas provides DataFrames, which are two-dimensional labeled data structures that allow for easy manipulation of tabular data. NumPy arrays serve as the backbone for these DataFrames.
  • Vectorized Operations: You can use NumPy functions directly within Pandas to do vectorized operations on DataFrame columns, so the computations are faster. For example, you can use 'np.add()' to add two columns element-wise.
  • Missing Data Handling: The NaN object of NumPy is used in Pandas to represent missing values, so it's easier to handle incomplete datasets.

28. Combining with Matplotlib for Visualization

Matplotlib is the base library for Python to generate static, animated, and interactive visualizations. It works nicely with NumPy and Pandas as well.

Python
import pandas as pd
import matplotlib.pyplot as plt

# Sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Plotting
df.plot(x='A', y='B', kind='line')
plt.title('Line Plot of A vs B')
plt.show()

29. Using SciPy for Scientific Computation

SciPy is based on NumPy with additional functionalities that are mainly focused on scientific computing:

  • Advanced Mathematical Functions: Optimization, Integration, Interpolation, Eigen value problems, etc.
  • Statistical Functions: SciPy offers numerous statistical tools for use with arrays of NumPy to analyze data with much more sophistication.
Python
from scipy import stats
import numpy as np

# Generating random data
data = np.random.normal(loc=0, scale=1, size=1000)

# Performing a statistical test
z_score = stats.zscore(data)
print("Z-scores:\n", z_score)

Common Errors and Troubleshooting in NumPy

When using NumPy users are bound to encounter a lot of errors that may disrupt their workflow. Being aware of common issues and their troubleshooting is necessary for effective programming. Below are some of the most frequent errors and their solutions.

30. Debugging Common Issues in NumPy Code

a. Memory Errors

One of the most common issues is the 'MemoryError', which occurs when NumPy cannot allocate enough memory for an operation. This often happens when working with large datasets or creating oversized arrays.

Solution

  • Optimize memory usage by using smaller data types or processing data in chunks.
  • Use 'np.empty()' instead of 'np.zeros()' or 'np.ones()' to create arrays without initializing values, which can save memory.
  • Consider chunking large datasets instead of loading them all at once.

b. Dtype Errors

Dtype errors occur when operations are attempted on incompatible data types. For example, trying to add a string to an integer array will raise a 'TypeError'.

Solution

  • Check the data type of your array using the '.dtype' attribute.
  • Use the 'astype()' method to convert the array to an appropriate type if necessary.

c. Import Errors

Users may encounter import errors if NumPy is not installed correctly or if there are version mismatches between NumPy and other libraries.

Solution

  • Make sure NumPy is installed in the right Python environment. You can check your installation with 'pip show numpy'.
  • If you have compatibility issues after upgrading, you might want to downgrade NumPy or reinstall dependent packages.

31. Exception Handling for Array Operations

You should handle exceptions well in your code so that it does not crash and gives meaningful error messages.

a. Using Try/Except Blocks

Use try/except blocks to catch and handle specific exceptions in your code.

Python
import numpy as np

try:
    # Example operation that may cause an error
    arr = np.array([1, 2, 'three'])
    arr_sum = np.sum(arr)
except TypeError as e:
    print("TypeError occurred:", e)

b. Checking Array Conditions

Check conditions such as array shapes and data types before performing operations to avoid runtime errors.

Python
if arr.ndim != 1:
    print("Array must be one-dimensional.")

Combined Snippet

Python
import numpy as np

# 1. Array Creation
# Creating 1D and 2D arrays
array_1d = np.array([1, 2, 3, 4, 5])
array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print("1D Array:\n", array_1d)   
print(' ')
print("2D Array:\n", array_2d)
print(' ')


# Using built-in functions
zeros_array = np.zeros((2, 3))
ones_array = np.ones((3, 3))
arange_array = np.arange(0, 10, 2)
linspace_array = np.linspace(0, 1, 5)

print("\nZeros Array:\n", zeros_array)
print(' ')
print("Ones Array:\n", ones_array)
print(' ')
print("Arange Array:\n", arange_array)
print(' ')
print("Linspace Array:\n", linspace_array)
print(' ')


# 2. Mathematical Operations
# Element-wise arithmetic operations
addition_result = array_1d + 10
multiplication_result = array_1d * 2

print("\nAddition Result:\n", addition_result)
print(' ')
print("Multiplication Result:\n", multiplication_result)
print(' ')

# Using universal functions (ufuncs)
squared_array = np.square(array_1d)
print("\nSquared Array:\n", squared_array)
print(' ')

# Aggregate functions
mean_value = np.mean(array_1d)
std_dev_value = np.std(array_1d)

print("\nMean Value:", mean_value)
print(' ')
print("Standard Deviation:", std_dev_value)
print(' ')

# 3. Indexing and Slicing
sliced_array = array_1d[1:4]
boolean_indexed_array = array_1d[array_1d > 2]

print("\nSliced Array (Index 1 to 3):\n", sliced_array)
print(' ')
print("Boolean Indexed Array (Values > 2):\n", boolean_indexed_array)
print(' ')

# 4. Reshaping and Flattening Arrays
reshaped_array = array_2d.reshape(3, 2) # Reshape to (3,2)
flattened_array = array_2d.flatten()

print("\nReshaped Array (3x2):\n", reshaped_array)
print(' ')
print("Flattened Array:\n", flattened_array)
print(' ')

# 5. Reading and Writing Data
# Saving an array to a text file
np.savetxt('array_data.txt', array_2d)

# Loading the saved data
loaded_data = np.loadtxt('array_data.txt')
print("\nLoaded Data from Text File:\n", loaded_data)
print(' ')

# Exception Handling Example
try:
    # Attempting an operation that may fail
    invalid_operation = np.array([1, 'two', 3]) + np.array([4, 5])
except TypeError as e:
    print("\nTypeError occurred:", e)
    print(' ')

# Conclusion: Demonstrating integration with other libraries (optional)
import pandas as pd
import matplotlib.pyplot as plt

# Creating a DataFrame from a NumPy array
df = pd.DataFrame(array_2d, columns=['Column1', 'Column2', 'Column3'])
print("\nDataFrame from NumPy Array:\n", df)

# Plotting the DataFrame using Matplotlib
df.plot(kind='bar')
plt.title('Bar Plot of DataFrame')
plt.xlabel('Index')
plt.ylabel('Values')
plt.show()

Output

1D Array:

[1 2 3 4 5]


2D Array:

[[1 2 3]

[4 5 6]]


Zeros Array:

[[0. 0. 0.]

[0. 0. 0.]]

Ones Array:

[[1. 1. 1.]

[1. 1. 1.]

[1. 1. 1.]]

Arange Array:

[0 2 4 6 8]


Linspace Array:

[0. 0.25 0.5 0.75 1. ]


Addition Result:

[11 12 13 14 15]


Multiplication Result:

[ 2 4 6 8 10]

Squared Array:

[ 1 4 9 16 25]


Mean Value: 3.0

Standard Deviation: 1.4142135623730951

Sliced Array (Index 1 to 3):

[2 3 4]


Boolean Indexed Array (Values > 2):

[3 4 5]


Reshaped Array (3x2):

[[1 2]

[3 4]

[5 6]]

Flattened Array:

[1 2 3 4 5 6]


Loaded Data from Text File:

[[1. 2. 3.]

[4. 5. 6.]]


TypeError occurred: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('int64')) -> None


DataFrame from NumPy Array:

Column1 Column2 Column3

0 1 2 3

1 4 5 6

1

Conclusion

In summary, NumPy is an important library for numerical computations in Python. It contains quick ways to generate arrays, highly mathematical and statistical operations, and even integrates with libraries such as Pandas and Matplotlib. The most salient characteristics include element-wise operations, different indices and slice techniques, broadcasting, and random number generators. Once mastery is gained over these functionality as well as common errors, efficiency in data manipulation and analysis is achieved: in short, NumPy should be the first choice for any data scientist or researcher.

Must read:


Next Article
Practice Tags :

Similar Reads