0% found this document useful (0 votes)
7 views

python 2.1.1 (2)

Module 2 introduces NumPy, focusing on its data types, array structures, and computational capabilities. Key concepts include the efficiency of NumPy arrays over Python lists, universal functions for element-wise operations, and aggregation functions for summarizing data. The module also covers advanced techniques like broadcasting, fancy indexing, and structured arrays for handling heterogeneous data.

Uploaded by

hritikp266
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

python 2.1.1 (2)

Module 2 introduces NumPy, focusing on its data types, array structures, and computational capabilities. Key concepts include the efficiency of NumPy arrays over Python lists, universal functions for element-wise operations, and aggregation functions for summarizing data. The module also covers advanced techniques like broadcasting, fancy indexing, and structured arrays for handling heterogeneous data.

Uploaded by

hritikp266
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Module 2: 1.

Introduction to NumPy: Understanding Data Types in Python, The Basics of NumPy


Arrays, Computation on NumPy Arrays: Universal Functions, Aggregations: Min, Max, and Everything
In Between, Computation on Arrays: Broadcasting, Comparisons, Masks, and Boolean Logic, Fancy
Indexing, Sorting Arrays, Structured Data: NumPy's Structured Arrays.

1. Introduction to NumPy: Understanding Data Types in Python

In Python, data types can be primitive types like int, float, or str, and they can also be
collections such as list, tuple, and dict. However, when working with large datasets or
performing heavy computations, Python's built-in data types aren't as efficient. NumPy
arrays are more optimized and allow operations on numerical data with great speed.

NumPy Data Types (dtypes)

NumPy arrays have a fixed size for each element and store elements of the same data type.
This makes them more efficient for numerical operations compared to Python's built-in data
types like lists.

 int: Represents integers.


 float: Represents floating-point numbers.
 complex: Represents complex numbers.
 bool: Represents boolean values (True or False).
 str: Represents string data.

Example:

import numpy as np

# Creating NumPy arrays with different dtypes


int_array = np.array([1, 2, 3], dtype='int32') # integer array
float_array = np.array([1.1, 2.2, 3.3], dtype='float64') # floating-point
array
bool_array = np.array([True, False, True], dtype='bool') # boolean array

print(int_array, int_array.dtype)
print(float_array, float_array.dtype)
print(bool_array, bool_array.dtype)

Output:

[1 2 3] int32
[1.1 2.2 3.3] float64
[ True False True] bool

Here, we created arrays of different types (int32, float64, bool) using the dtype
parameter.
2. The Basics of NumPy Arrays

NumPy arrays are the core data structure in NumPy. They are efficient, multidimensional
containers that can store elements of the same type. These arrays are faster and require less
memory than standard Python lists.

Creating a NumPy Array

You can create NumPy arrays using the np.array() function.

Example:

import numpy as np

# 1D Array (Vector)
arr_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr_1d)

# 2D Array (Matrix)
arr_2d = np.array([[1, 2], [3, 4], [5, 6]])
print("2D Array:\n", arr_2d)

# 3D Array
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("3D Array:\n", arr_3d)

Output:

1D Array: [1 2 3 4 5]
2D Array:
[[1 2]
[3 4]
[5 6]]
3D Array:
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

 arr_1d is a one-dimensional array.


 arr_2d is a two-dimensional array (matrix).
 arr_3d is a three-dimensional array.

3. Computation on NumPy Arrays: Universal Functions (ufuncs)

Universal Functions (ufuncs) are functions that operate element-wise on NumPy arrays.
They are highly optimized and allow operations to be performed on the entire array at once,
instead of looping over elements individually.

Example of Universal Functions:


import numpy as np

# Arrays for operations


arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([10, 20, 30, 40])

# Element-wise addition
result_add = np.add(arr1, arr2)
print("Addition:", result_add)

# Element-wise multiplication
result_mul = np.multiply(arr1, arr2)
print("Multiplication:", result_mul)

# Square root of each element


result_sqrt = np.sqrt(arr1)
print("Square Root:", result_sqrt)

Output:

Addition: [11 22 33 44]


Multiplication: [ 10 40 90 160]
Square Root: [1. 1.41421356 1.73205081 2. ]

Here, we applied addition, multiplication, and square root operations element-wise to the
arrays using the corresponding universal functions.

4. Aggregations: Min, Max, and Everything In Between

NumPy provides several aggregation functions like np.min(), np.max(), np.sum(), and
np.mean() to perform quick calculations on the entire array or along specific axes
(rows/columns).

Example of Aggregation:

import numpy as np

# Array for aggregation


arr = np.array([1, 2, 3, 4, 5])

# Min and Max


print("Min:", np.min(arr))
print("Max:", np.max(arr))

# Sum and Mean


print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))

Output:

Min: 1
Max: 5
Sum: 15
Mean: 3.0
Here, we calculated the minimum, maximum, sum, and mean of the array.

5. Computation on Arrays: Broadcasting, Comparisons, Masks, and Boolean


Logic

Broadcasting:

Broadcasting is a powerful feature that allows NumPy to perform element-wise operations on


arrays of different shapes by automatically expanding the smaller array to match the
dimensions of the larger one.

Example of Broadcasting:

import numpy as np

arr1 = np.array([1, 2, 3])


arr2 = np.array([10])

# Broadcasting arr2 to match the shape of arr1


result = arr1 + arr2
print("Result after Broadcasting:", result)

Output:

Result after Broadcasting: [11 12 13]

In this case, arr2 (which is a scalar) is broadcasted to each element of arr1, so the operation
is performed element-wise.

Comparisons and Boolean Logic:

You can compare arrays element-wise, resulting in a boolean array, and apply logical
operations.

Example of Comparison and Boolean Masking:

arr = np.array([1, 2, 3, 4, 5])

# Boolean comparison (greater than 3)


mask = arr > 3
print("Mask (arr > 3):", mask)

# Using the mask to filter the array


filtered_arr = arr[mask]
print("Filtered Array:", filtered_arr)

Output:

Mask (arr > 3): [False False False True True]


Filtered Array: [4 5]
Here, we created a mask that checks which elements are greater than 3 and then used it to
filter the array.

6. Fancy Indexing

Fancy indexing allows you to index arrays using other arrays (or lists), rather than just
integers. This technique provides more flexibility.

Example of Fancy Indexing:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

# Fancy indexing with an index array


indices = np.array([0, 2, 4])
result = arr[indices]
print("Fancy Indexing Result:", result)

Output:

Fancy Indexing Result: [10 30 50]

Here, we used an index array to select the elements at positions 0, 2, and 4.

7. Sorting Arrays

Sorting arrays is a common operation. NumPy provides the np.sort() function for sorting
arrays.

Example of Sorting:

arr = np.array([3, 1, 2, 5, 4])

# Sorting the array in ascending order


sorted_arr = np.sort(arr)
print("Sorted Array:", sorted_arr)

Output:

Sorted Array: [1 2 3 4 5]

Here, we sorted the array in ascending order.

8. Structured Data: NumPy's Structured Arrays


Structured arrays allow you to store heterogeneous data types (like records or tables). Each
element can contain multiple fields, which makes it possible to represent complex data.

Example of Structured Arrays:

import numpy as np

# Define a structured data type with fields 'name' and 'age'


dt = np.dtype([('name', 'U10'), ('age', 'i4')])

# Create an array of structured data


people = np.array([('Alice', 25), ('Bob', 30), ('Charlie', 35)], dtype=dt)

print("Structured Array:\n", people)

Output:

Structured Array:
[('Alice', 25) ('Bob', 30) ('Charlie', 35)]

In this example, we created a structured array where each element has two fields: name (a
string of 10 characters) and age (an integer).

Summary of Key Concepts

 NumPy arrays are efficient, fixed-size containers for numerical data.


 Universal Functions (ufuncs) allow element-wise operations on arrays.
 Aggregation functions like np.min(), np.max(), and np.mean() help you
summarize data.
 Broadcasting allows operations on arrays of different shapes.
 Fancy indexing allows advanced indexing techniques to access elements.
 Structured arrays enable storage of heterogeneous data types.

 Sure! Below are 15 easier theory-based questions on NumPy concepts that students
can answer with concise explanations. These questions are designed to test basic
understanding and are more approachable for students:

Explain the concept of NumPy data types (dtypes). What are the common dtypes used in NumPy
arrays?

What are NumPy arrays, and how do they differ from Python lists in terms of performance and
functionality?

Explain how the aggregation functions np.min(), np.max(), and np.mean() are used on NumPy
arrays. Provide examples.

Describe what fancy indexing in NumPy is and give an example of how it is used to access
elements in an array.
Explain how the np.sort() function is used to sort a NumPy array. What is the default sorting
order?

Compare NumPy arrays and Python lists. Discuss the advantages of using NumPy arrays for
numerical computations.

What are the key differences between a 1D, 2D, and 3D NumPy array? Provide examples of each.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy