Python Numpy 101: How to Index Elements in Numpy Arrays?

Daily Data Science Puzzle

import numpy as np

# air quality index AQI data
hong_kong = np.array(
    [ 42, 40, 41, 43, 44, 43 ])
new_york = np.array(
    [ 30, 31, 29, 29, 29, 30 ])
montreal = np.array(
    [ 11, 11, 12, 13, 11, 12 ])

hk_mean = (hong_kong[0] + hong_kong[-1]) / 2.0
ny_mean = (new_york[1] + new_york[-3]) / 2.0
m_mean = (montreal[1] + montreal[-0]) / 2.0

print(hk_mean)
print(ny_mean)
print(m_mean)

What is the output of this puzzle?
*Beginner Level* (solution below)

Numpy is a popular Python library for data science for array, vector, and matrix computations. This puzzle introduces basic indexing of elements in numpy arrays.

The puzzle analysis data from the real-time air quality index (AQI) for the three cities Hong Kong, New York, and Montreal. The index data aggregates various factors that influence the air quality such as respirable particulate matter, ozone, and nitrogen dioxide. The goal is to compare the air quality data for the three cities. To show how indexing works, we use different indexing schemes to access two data values for each city. Then, we normalize the data by 2.0.

You can use positive or negative indices. For positive indices, use 0 to access the first element and increment the index by 1 to index each subsequent element. For negative indices, use -1 to access the last element and decrement the index by 1 to access each previous element. It’s as simple as that.


Are you a master coder?
Test your skills now!

Related Video

Solution

42.5
30.0
11.0

 

Leave a Comment