Reading and Selecting N-Dimensional Arrays

N-Dimensional Arrays organize numerical measurements so that each position has a clear meaning. You might store time along one direction and sensor number along another, or add a third direction for repeated experiments. In Python, NumPy provides the array structure used here. You will create arrays, inspect their organization, and select exactly the entries you need.

Create an array and read its shape

An N-dimensional array is a rectangular collection of elements described by NN axes. An axis need not represent a physical direction: it might identify time, a sensor, or an experiment. A numerical NumPy array stores its elements using one dtype, such as an integer or floating-point type.


Example: Create two rows of three values from nested Python tuples. Equal-length nested lists also work.


Python
import numpy as np

a = np.array(((2, 4, 6), (8, 10, 12)), dtype=float)


The shape is the ordered tuple of axis lengths. Here, a.shape is (2, 3), a.ndim is 2, and a.size is 6. These describe axis lengths, number of axes, and total number of elements, respectively. For NN axes with lengths d0d_0 through dN−1d_{N-1}:


size=∏k=0N−1dk\text{size} = \prod_{k=0}^{N-1} d_k


A two-dimensional array has two rows and three columns, with zero-based indices beside each axis.


The distinction matters even when arrays contain the same number of values.


Shape

Number of axes

Organization

(4,)

1

One sequence of four elements

(1, 4)

2

One row and four columns

(4, 1)

2

Four rows and one column


The comma in (4,) is Python notation for a one-entry tuple; it does not introduce another axis.

Generate values and reshape them

Use np.zeros((2, 3)) to create six zeros already arranged in two rows. For an integer sequence, np.arange(6) generates the values zero through five. Its stopping value is excluded.


Python
sequence = np.arange(6)
b = sequence.reshape(2, 3)


Reshaping assigns new axis lengths while preserving the element count. With the default order used here, the last axis changes fastest, so the first row of b contains zero, one, and two; the second contains three, four, and five. The original variable sequence still has shape (6,).



Reshaping does not infer scientific meaning. If rows should represent times and columns should represent sensors, check that the incoming sequence follows that arrangement. Reshaping also does not guarantee independent storage; use .copy() when independence is required.

Select positions and ranges

Indices start at zero. For the array a, a[1, 2] selects the second row and third column, giving 12.0. A negative index counts from the end, so a[1, -1] selects the same entry.


A slice uses start:stop:step. With a positive step, the start is included and the stop is excluded. An omitted step means one, and : selects an entire axis.


Python
row = a[1, :]
row_block = a[1:2, :]
columns = a[:, 0:3:2]


An integer index removes its selected axis, whereas a slice retains it. Consequently, row.shape is (3,), row_block.shape is (1, 3), and columns.shape is (2, 2).



What to remember

  • Read shape entries in axis order; multiply them to obtain size.
  • Preserve the element count when reshaping.
  • Count indices from zero and exclude a slice's stop.
  • Integer indices remove axes; slices retain axes.
  • Copy a basic slice when later edits should be independent.

Example: Organizing a temperature log

Example: A logger records four temperature channels at each of three successive times. Its twelve readings, in °C, are the consecutive integers from 18 through 29. The first four readings belong to the first time, the next four to the second time, and the final four to the third time. Store them as floating-point values.


Python
import numpy as np
raw = np.arange(18, 30, dtype=float)


The channel and time numbers below use ordinary counting from one; array indices start at zero.


a) Construct an array t with times as rows and channels as columns. State its shape, number of axes, and total element count.


The sequence begins at ________ and ends at ________, since the integer stop 30 is excluded. It contains 30−18=1230-18=12 readings.


The shape gives the ordered axis lengths. Three times require three rows, and four channels require four columns. Their product is 3×4=123\times4=12, matching the available readings.


Python
t = raw.reshape(3, 4)


The default reshape order fills the channel positions across each time row before moving to the next row. The rows therefore contain 18–21 °C, 22–25 °C, and 26–29 °C.


Answer: t.shape is (3, 4), t.ndim is 2, and t.size is 12 readings.


b) Retrieve the temperature at the second time from the fourth channel using one integer index for each axis.


Convert the ordinary time and channel numbers to zero-based indices. The time index is ________, and the channel index is ________. The requested expression is therefore t[1, 3].


One complete time row contains four readings. Starting from 18 °C, move past four readings for the time index and then three positions for the channel index:


18 °C+(1×4+3)(1 °C)=25 °C.18\ \text{°C}+(1\times4+3)(1\ \text{°C})=25\ \text{°C}.


Both axes receive integer indices, so the result is a single numerical value rather than a two-dimensional region.


Answer: t[1, 3] returns 25.0 °C.


c) Extract the second and third times and the second and fourth channels into an independent array chosen. State its shape and readings.


The requested row indices are ________, so the row slice is 1:3. The requested column indices are ________, so the column slice is 1:4:2. Each slice excludes its stopping index.


A basic slice shares data with its source. Add .copy() because later edits must be independent.


Python
chosen = t[1:3, 1:4:2].copy()


At the second time, the selected channels contain 23.0 °C and 25.0 °C. At the third time, they contain 27.0 °C and 29.0 °C. Both selections use slices, so both axes remain present.


Answer: chosen.shape is (2, 2). Its first row contains 23.0 °C and 25.0 °C, and its second row contains 27.0 °C and 29.0 °C. Changing chosen afterward leaves t unchanged.

A laboratory assistant stores five measured lengths in metres using the following Python code. Which statement correctly describes the resulting array?


Python
import numpy as np
lengths = np.array((3.2, 4.1, 5.6, 6.8, 7.0))
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A laboratory team is replacing Python loops with NumPy calculations. Match each term to the description that best identifies its role in array-based calculations.

Match each term
A.

Combining values along selected axes into summaries such as sums or means.

B.

A NumPy callable such as np.sqrt that acts element by element and supports compatible input shapes.

C.

Aligning compatible input shapes so arrays with different shapes can participate in an operation.

D.

Expressing a calculation through whole-array operations rather than writing a Python loop over individual entries.

Broadcasting

Vectorization

Reduction

Universal function

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A technician creates the integer identifiers ids = np.arange(60, 84) after importing NumPy as np. Each table row proposes a separate reshape of this original array. Replace each question mark with the positive integer that makes the reshape valid. Enter exact integers.

Proposed shapeMissing axis length
(4, ?, 3)
(?, 6)
(?,)
(2, 2, ?)

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice