📖 Scenario: Imagine you have a small dataset of daily temperatures recorded over a week for different cities. You want to select specific days and cities to analyze the temperature trends.
🎯 Goal: You will create a NumPy array with temperature data, set up an index list for cities, use fancy and slice indexing together to select data, and finally print the selected temperatures.
📋 What You'll Learn
Create a 2D NumPy array called temps with shape (7, 4) representing 7 days and 4 cities.
Create a list called city_indices containing the city indices 0 and 2.
Use fancy indexing with city_indices and slice indexing for days 2 to 5 (inclusive start, exclusive end) on temps.
Print the resulting selected temperatures.
💡 Why This Matters
🌍 Real World
Selecting specific rows and columns from data is common in data science when analyzing subsets of data, like temperatures for certain days and cities.
💼 Career
Data scientists often use fancy and slice indexing in NumPy to efficiently manipulate and analyze large datasets.
Progress0 / 4 steps
1
Create the temperature data array
Create a NumPy array called temps with these exact values representing temperatures for 7 days (rows) and 4 cities (columns): [[30, 32, 31, 29], [31, 33, 30, 28], [29, 31, 32, 30], [28, 30, 29, 27], [27, 29, 28, 26], [26, 28, 27, 25], [25, 27, 26, 24]].
NumPy
Hint
Use np.array([...]) with the exact nested list of temperatures.
2
Create the city indices list
Create a list called city_indices containing the integers 0 and 2 to select the first and third cities.
NumPy
Hint
Use a list with the exact values [0, 2].
3
Select temperatures using fancy and slice indexing
Create a variable called selected_temps that selects rows from day 2 to day 5 (use slice 2:6) and columns using the city_indices list from the temps array.
NumPy
Hint
Use temps[2:6, city_indices] to combine slice and fancy indexing.
4
Print the selected temperatures
Print the variable selected_temps to display the selected temperature data.
NumPy
Hint
Use print(selected_temps) to show the result.
Practice
(1/5)
1. What does combining fancy indexing and slice indexing in NumPy allow you to do? arr[[0, 2], 1:4] selects:
easy
A. Rows 0 to 2, columns 1 and 4
B. Rows 1 to 4, columns 0 and 2
C. Rows 0 and 2, columns 1 to 3
D. Rows 1 and 4, columns 0 to 2
Solution
Step 1: Understand fancy indexing for rows
The fancy index [0, 2] selects rows 0 and 2 specifically.
Step 2: Understand slice indexing for columns
The slice 1:4 selects columns starting at 1 up to but not including 4, so columns 1, 2, and 3.