Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Assigning Values to Indexed Subarrays | Section
Numerical Computing with NumPy
Avsnitt 1. Kapitel 17
single

single

bookAssigning Values to Indexed Subarrays

Svep för att visa menyn

With indexed arrays, things start getting more interesting. Here we'll focus on 1D and 2D subarrays, as 3D subarrays are rarely used in practice.

Let's first start with assigning values to slices. The general syntax looks like this: slice = values, where slice is a slice of a certain array and values are the values to be assigned.

Possible formats of values:

  • a single scalar (number);
  • a 1D array of the same size as the slice (if it is 1D); or the size of the second dimension (if the slice is 2D);
  • a 2D array of the same shape as a 2D slice.
123456789101112131415161718
import numpy as np array_1d = np.array([1, 4, 6, 2, 9]) # Assigning an array to the slice of array_1d array_1d[1:-1] = np.array([3, 5, 7]) print(array_1d) # Assigning a scalar to the slice of array_1d array_1d[1:-1] = 5 print(array_1d) array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) # Assigning a 2D array to the slice of array_2d array_2d[1:3, 1:] = np.array([[20, 21], [40, 41]]) print(array_2d) # Assigning a 1D array to the slice of array_2d array_2d[1:3, 1:] = [50, 51] print(array_2d) # Assigning a scalar to the slice of array_2d array_2d[1:3, 1:] = 30 print(array_2d)
copy

When we assign a scalar to a 1D slice, this scalar is assigned to every element of the slice. When a 1D array is assigned to a 2D slice, this 1D array is assigned to every 1D array in the slice. Assigning a scalar to a 2D slice works the same as with a 1D slice.

Assigning values to integer array indexed subarrays works the same way as with slices. Assigning values to boolean indexed subarrays works the same way as with 1D slices.

Uppgift

Swipe to start coding

You are managing a dataset of product prices and ratings. The prices are stored in the prices array, and the ratings (out of 10) are stored in the ratings array, where each row represents a different product category. Your task is to update the prices and ratings based on specific criteria:

  1. Assign the value of 20 to every element in prices greater than 10 (boolean indexing) using a scalar.
  2. Assign a NumPy array with elements 9, 8 to the last two elements of the second row (second 1D array) of ratings. Use a positive row index and a slice specifying only start (positive index).

Lösning

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 17
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt