NumPy Arrays in Python
18 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which of the following statements best describes the key difference between Python lists and NumPy arrays?

  • Python lists can store elements of different data types, while NumPy arrays are designed for homogeneous data types. (correct)
  • Python lists require importing the NumPy library, while NumPy arrays do not.
  • Python lists are more efficient for numerical operations than NumPy arrays.
  • Python lists can only store numbers, while NumPy arrays can store any data type.

The ndarray.size attribute in NumPy returns the size in bytes of each element in the array.

False (B)

Write the code to create a 2x3 NumPy array filled with the value 7.

np.full((2, 3), 7)

The NumPy function np._______(shape) creates an array filled with zeros.

<p>zeros</p> Signup and view all the answers

Match the NumPy array attributes with their descriptions:

<p><code>ndarray.ndim</code> = Number of dimensions of the array <code>ndarray.shape</code> = Dimensions of the array <code>ndarray.dtype</code> = Data type of the elements <code>ndarray.itemsize</code> = Size in bytes of each element</p> Signup and view all the answers

Given a NumPy array arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), what does arr[1:, :2] return?

<p><code>array([[4, 5], [7, 8]])</code> (D)</p> Signup and view all the answers

Arrays are useful for storing and manipulating small amounts of data inefficiently.

<p>False (B)</p> Signup and view all the answers

In NumPy, how do you create an array without initializing the values?

<p><code>np.empty(shape)</code></p> Signup and view all the answers

What is the key difference between ndarray.ravel() and ndarray.flatten() when used to convert a multi-dimensional NumPy array into a one-dimensional array?

<p><code>ravel()</code> returns a view of the original array if possible, while <code>flatten()</code> always returns a copy. (C)</p> Signup and view all the answers

If two NumPy arrays have different dimensions, broadcasting will always fail.

<p>False (B)</p> Signup and view all the answers

How can you create an independent copy of a NumPy array named arr?

<p>arr.copy()</p> Signup and view all the answers

To join two NumPy arrays horizontally, you would use the __________ function.

<p>np.hstack()</p> Signup and view all the answers

Match the NumPy functions with their corresponding descriptions.

<p>np.sum(arr) = Calculates the sum of all elements in the array np.mean(arr) = Calculates the arithmetic mean of the elements in the array np.std(arr) = Calculates the standard deviation of the elements in the array np.median(arr) = Calculates the median of the elements in the array</p> Signup and view all the answers

What is the correct way to reshape a NumPy array arr with shape (6,) into a 2x3 array?

<p><code>arr.reshape(2, 3)</code> (A)</p> Signup and view all the answers

Assigning one array to another array (e.g., arr1 = arr2) creates a new, independent copy of the array.

<p>False (B)</p> Signup and view all the answers

What NumPy function splits an array into multiple sub-arrays?

<p>np.split()</p> Signup and view all the answers

Which of the following operations is performed element-wise on NumPy arrays?

<p>Array addition using <code>arr1 + arr2</code> (D)</p> Signup and view all the answers

If arr1 has a shape of (3, 1) and arr2 has a shape of (3, 3), broadcasting allows the operation arr1 + arr2. In this case, arr1 is effectively __________ along its columns to match the shape of arr2.

<p>repeated</p> Signup and view all the answers

Flashcards

What is Python?

A versatile language known for readability and extensive libraries.

What is an array?

A collection of same-typed elements in contiguous memory.

NumPy's advantage?

NumPy excels in numerical operations due to vectorized operations.

How to import NumPy?

Import NumPy as np.

Signup and view all the flashcards

What does np.zeros(shape) do?

Creates an array filled with zeros.

Signup and view all the flashcards

What is ndarray.ndim?

Number of array dimensions.

Signup and view all the flashcards

What is ndarray.shape?

A tuple representing array dimensions.

Signup and view all the flashcards

What does arr[0, 1] do?

Accesses the element at the first row and second column.

Signup and view all the flashcards

Element-wise operations

Applies an operation (+, -, *, /) to each corresponding element in the arrays.

Signup and view all the flashcards

Scalar operation

Applies an operation to each element in the array, using a single value.

Signup and view all the flashcards

Aggregation functions

Calculates statistics like sum, mean, median etc. across array elements.

Signup and view all the flashcards

Array Reshaping

Changes the dimensions of an array without changing its data.

Signup and view all the flashcards

Flattening Arrays

Transforms a multi-dimensional array into a one-dimensional array.

Signup and view all the flashcards

Array Concatenation

Joins arrays together along a specified axis (horizontally or vertically).

Signup and view all the flashcards

Array Splitting

Splits an array into multiple sub-arrays.

Signup and view all the flashcards

Broadcasting

Allows operations on arrays with different shapes by virtually expanding the smaller array.

Signup and view all the flashcards

Broadcasting Rule 1

NumPy expands dimensions of the smaller array by adding 1s until dimensions match.

Signup and view all the flashcards

Array Copying

Creates a completely new array with copied data, independent of the original.

Signup and view all the flashcards

Study Notes

  • Python is a versatile programming language known for its readability and extensive libraries.
  • Arrays in Python are typically handled using the NumPy library, which provides efficient array operations.

Array Concepts in Python

  • An array is a collection of elements of the same data type, residing in contiguous memory locations.
  • Arrays are useful for efficiently storing and manipulating large amounts of data.
  • Python lists can store elements of different types, while NumPy arrays are designed for homogenous data types.
  • NumPy arrays offer better performance for numerical operations compared to Python lists, due to vectorized operations.

Creating Arrays using NumPy

  • To create arrays in Python, import the NumPy library: import numpy as np.
  • Arrays can be created from Python lists using np.array(): arr = np.array([1, 2, 3, 4, 5]).
  • NumPy offers functions to create arrays with specific initial values:
    • np.zeros(shape): Creates an array filled with zeros.
    • np.ones(shape): Creates an array filled with ones.
    • np.empty(shape): Creates an array without initializing values.
    • np.full(shape, value): Creates an array filled with a specified value.
  • The shape argument is a tuple that specifies the dimensions of the array (e.g., (3, 4) for a 3x4 array).

Array Attributes

  • ndarray.ndim: Represents the number of dimensions (axes) of the array.
  • ndarray.shape: Represents the dimensions of the array.
  • ndarray.size: Represents the total number of elements in the array.
  • ndarray.dtype: Represents the data type of the elements in the array.
  • ndarray.itemsize: Represents the size in bytes of each element in the array.

Array Indexing and Slicing

  • Array elements can be accessed using their index, starting from 0.
    • For one-dimensional arrays: arr[0] accesses the first element.
    • For multi-dimensional arrays: arr[0, 1] accesses the element at the first row and second column.
  • Slicing allows extracting subarrays from an array:
    • arr[start:end] extracts elements from start index to end-1 index.
    • arr[:end] extracts elements from the beginning to end-1 index.
    • arr[start:] extracts elements from start index to the end.
    • arr[:] creates a copy of the entire array.
  • For multi-dimensional arrays, slicing can be applied to each dimension: arr[0:2, 1:3].

Array Operations

  • NumPy arrays support element-wise operations:
    • Addition: arr1 + arr2
    • Subtraction: arr1 - arr2
    • Multiplication: arr1 * arr2
    • Division: arr1 / arr2
  • Scalar operations apply the operation to each element in the array: arr + 5.
  • NumPy provides various mathematical functions that can be applied to arrays:
    • np.sin(arr): Calculates the sine of each element.
    • np.cos(arr): Calculates the cosine of each element.
    • np.sqrt(arr): Calculates the square root of each element.
    • np.exp(arr): Calculates the exponential of each element.
  • Aggregation functions compute statistics on array elements:
    • np.sum(arr): Calculates the sum of all elements.
    • np.mean(arr): Calculates the mean of all elements.
    • np.median(arr): Calculates the median of all elements.
    • np.min(arr): Finds the minimum value.
    • np.max(arr): Finds the maximum value.
    • np.std(arr): Calculates the standard deviation.

Array Reshaping

  • The shape of an array can be changed without changing its data using ndarray.reshape():
    • arr = np.array([1, 2, 3, 4, 5, 6])
    • new_arr = arr.reshape((2, 3)) # Reshapes to a 2x3 array
  • ndarray.ravel() or ndarray.flatten() can be used to flatten a multi-dimensional array into a one-dimensional array.
    • ravel() returns a view of the original array if possible, while flatten() always returns a copy.

Array Concatenation and Splitting

  • np.concatenate((arr1, arr2), axis) joins two or more arrays along a specified axis.
  • np.vstack((arr1, arr2)) stacks arrays vertically (row-wise).
  • np.hstack((arr1, arr2)) stacks arrays horizontally (column-wise).
  • np.split(arr, indices_or_sections, axis) splits an array into multiple sub-arrays. indices_or_sections can be an integer specifying the number of equal sections or a sorted array of indices where the splits will occur.

Broadcasting

  • Broadcasting allows NumPy to perform operations on arrays with different shapes.
  • NumPy automatically expands the dimensions of the smaller array to match the larger array.
  • Broadcasting rules:
    • If the arrays do not have the same number of dimensions, prepend the shape of the smaller array with 1s until the dimensions match.
    • If the size of a dimension does not match, but one of the dimensions has a size of 1, the array with size 1 is broadcast along that dimension.
    • If neither of the dimensions matches and neither has a size of 1, broadcasting fails.

Array Copying

  • Assigning an array to another variable does not create a new array; it creates a new reference to the same array:
    • arr1 = arr2 # arr1 and arr2 point to the same array
  • To create a new copy of an array, use ndarray.copy():
    • arr2 = arr1.copy() # arr2 is a new array with the same data as arr1

Example MCQs topics

  • Creating a NumPy array from a Python list.
  • Accessing elements in a multi-dimensional array using indexing.
  • Slicing a NumPy array to extract a subarray.
  • Performing element-wise arithmetic operations on arrays.
  • Reshaping a NumPy array to a different shape.
  • Using boolean indexing to filter array elements.
  • Calculating the sum, mean, or other statistics of array elements.
  • Concatenating two or more arrays along a specified axis.
  • Understanding broadcasting rules for array operations.
  • Creating a copy of an array vs. creating a view of an array.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Description

Learn about arrays in Python using NumPy. Explore array creation, attributes, and manipulation methods. NumPy arrays provide efficient storage and operations for numerical data.

More Like This

Use Quizgecko on...
Browser
Browser