0
0
NumPydata~15 mins

Combining fancy and slice indexing in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Combining fancy and slice indexing
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(selected_temps) to show the result.