3.1. Arrays Basics#
NumPy arrays store numbers of one type in compact blocks and operate on them quickly, which makes them the base of data analysis in Python. This section introduces the ndarray: how scalars, vectors, and matrices relate to array dimensions, how arrays store their values, and how to create and inspect them.
3.1.1. NumPy Arrays#
NumPy arrays, (N-dimensional arrays, or ndarray) are a powerful extension of Python lists, offering compact storage and fast operations for numerical data in rows and columns.
In NumPy, the terms scalar, vector, and matrix refer to specific dimensions of these arrays.
Fig. 3.1 Scalar, Vector, Matrix, and Tensor (Harshit Tyagi )#
NumPy is Python’s core library for numerical arrays, and its terms come from linear algebra, which is widely used in data science. Some of the essential terms are (Tyagi, 2020):
Scalar: Any single numerical value is a scalar, as shown in the image above. It is simply denoted by lowercase and italics. For example:
n.Vector: An array of numbers(data) is a vector. You can assume a column in a dataset to be a feature vector.
Matrix: A matrix is a 2-D array of shape (m×n) with m rows and n columns.
Tensor: Generally, an n-dimensional array where n>2 is called a Tensor. But a matrix or a vector is also a valid tensor.
While NumPy arrays can have any number of dimensions, the most common are:
Vectors: 1-dimensional arrays with a single axis
Matrices: 2-dimensional arrays with two axes (rows and columns)
3.1.1.1. NumPy Data Structure#
The primary data structure in NumPy is the N-dimensional array, or ndarray. A NumPy array can look like a list of lists in Python, but it is more compact than a Python list. In essence, a Python list is an array of pointers to heterogeneous Python objects, while a NumPy array is an array of uniform values of the same type (e.g., all integers, all floats) and array elements are stored in one continuous block of memory, similar to how arrays work in C (Fig. 3.2). Python lists are more flexible, but NumPy arrays use less memory, and access in reading and writing items is much faster (Martelli, 2009), which is a huge advantage when dealing with large datasets.
Fig. 3.2 Difference between NumPy array (C) and Python lists (Vanderplas, 2022)#
In short, NumPy’s primary data structure is the ndarray (N-dimensional array), which is a homogeneous, multidimensional array of fixed-size items. This means all elements within a ndarray must be of the same data type (note: To store heterogeneous data, NumPy uses structured arrays). While Python defines only one type of a particular data class (there is only one integer type, one floating-point type, etc.), there are 24 new fundamental Python types to describe different types of scalars in NumPy.
Fig. 3.3 Hierarchy of type objects representing the array data types (NumPy: Scalars )#
Compared some of the NumPy built-in types to Python built-in types:
Python type |
NumPy type |
Type name |
Type code |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
variable-length |
|
|
|
|
|
|
|
variable-length |
|
(all others) |
|
|
|
3.1.2. Using NumPy#
NumPy is not part of Python’s standard library, so you use it in two steps: install it once in your project’s virtual environment, then import it at the top of each notebook or script that uses it.
Installing NumPy
:class: dropdown
To install NumPy, you would:
Go to the command line
Navigate to your project directory (dsm)
Activate the virtual environment
Use the
pip install [package]syntax to install:
pip install numpy
You should see the installation happen like this:
(.venv) [username]@[computer]:~/workspace/dsm$ pip install numpy
Collecting numpy
Downloading numpy-2.3.3-cp312-cp312-macosx_14_0_arm64.whl.metadata (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.1/62.1 kB 1.3 MB/s eta 0:00:00
Downloading numpy-2.3.3-cp312-cp312-macosx_14_0_arm64.whl (5.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.1/5.1 MB 4.1 MB/s eta 0:00:00
Installing collected packages: numpy
Successfully installed numpy-2.3.3
Alternatively, in the Jupyter notebook, you may use the %pip install [package] syntax in a code cell to install packages just like pip install [package] in the command line. You will also see people use the older syntax !pip install, which runs pip as a shell command, while %pip is a Jupyter magic function that runs in the current notebook kernel.
Don’t forget to comment out (#) your pip commands in the cells after installation, or they’ll run every time you run the cell.
3.1.2.1. import NumPy#
Once you’ve installed NumPy, you can import it as a library and give it an alias; by convention, it is called np:
import numpy as np
Here, np is an alias for numpy, so you can write np.array() instead of numpy.array().
After you import the library, you use the dot operator to access the functions and attributes inside the module/library. Just type the name of the object, and then the dot (.) and the Tab key to show the menu. You can scroll down to select a function. In this case, choose the array function (note: the Tab key can also do autocompletion).
Fig. 3.4 Using the dot operator and Tab completion in NumPy#
3.1.2.2. Functions/Methods#
NumPy provides many functions for creating and operating on arrays. NumPy functions are called through the np namespace, such as np.array() and np.sum(). Many operations that act on an existing array are also available as array methods, called through the array object, such as arr.reshape() and arr.sum().
Array-creation routines such as np.array(), np.arange(), np.zeros(), and np.linspace() are naturally expressed as functions because they do not require an existing array. Other operations may be available as a function, a method, or both.
Category |
Function / Method |
Description |
Example |
|---|---|---|---|
Array Creation |
|
Create an array from array-like data |
|
|
Create evenly spaced values within an interval |
|
|
|
Create a specified number of evenly spaced values |
|
|
|
Create an array filled with zeros |
|
|
|
Create an array filled with ones |
|
|
|
Create a 2-D array with ones on the diagonal |
|
|
|
Create an array filled with a specified value |
|
|
Shape Operations |
|
Return an array with a new shape |
|
|
Return a flattened copy of an array |
|
|
|
Permute an array’s axes |
|
|
|
Join arrays along an existing axis |
|
|
|
Join arrays along a new axis |
|
|
Indexing / Selection |
|
Return indices satisfying a condition, or select values conditionally |
|
|
Return indices of nonzero elements |
|
|
|
Select values using multiple conditions |
|
|
Array Operations |
|
Sum array elements |
|
|
Sort array elements |
|
|
|
Return indices that would sort an array |
|
|
|
Return the unique values in an array |
|
The shape operations are covered in Combining and Reshaping Arrays below, and sum(), sort(), and argsort() in Array Computation.
3.1.3. Creating NumPy Arrays#
3.1.3.1. array([sequence])#
You can create an array by directly converting a list to an array. First, create a list:
num_list = [1,2,3, 4, 5]
print("num_list: ", num_list)
print("num_list type:", type(num_list))
num_list: [1, 2, 3, 4, 5]
num_list type: <class 'list'>
Now convert the list into a numpy array using numpy’s array() function to create a 1-D array.
arr = np.array(num_list) ### casting a list to a numpy array
arr
array([1, 2, 3, 4, 5])
Now create a 2-D (rows and columns) array using a 2-D tuple:
arr_2d = np.array(
(
[1,2,3],
[4,5,6],
[7,8,9]
)
)
arr_2d
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
An example of Python 3-D list, which is a list of lists:
list_of_list = [
[
[1, 2, 3],
[2, 2, 3],
],
[
[3, 2, 3],
[4, 2, 3]
],
[
[5, 2, 3],
[6, 2, 3]
]
]
list_of_list
[[[1, 2, 3], [2, 2, 3]], [[3, 2, 3], [4, 2, 3]], [[5, 2, 3], [6, 2, 3]]]
Compare the output of the Python list above with the NumPy array created from the list:
np.array(list_of_list)
array([[[1, 2, 3],
[2, 2, 3]],
[[3, 2, 3],
[4, 2, 3]],
[[5, 2, 3],
[6, 2, 3]]])
You can check the data type of the arrays to see they are truly arrays:
print(type(arr))
print(type(arr_2d))
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
### 1 Exercise: Create a 3-D NumPy array from the following
### list of lists and print its type and shape:
import numpy as np
data_3d = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
[[9, 10], [11, 12]]
]
### Your code starts here:
### Your code ends here.
<class 'numpy.ndarray'>
(3, 2, 2)
3.1.3.2. The arange() Function#
numpy.arange() is a NumPy function used to create arrays with evenly spaced values with a specified interval. It is similar to Python’s built-in range() function, but returns a NumPy ndarray instead of a range object, which is more efficient for numerical operations.
np.arange(5)
array([0, 1, 2, 3, 4])
Using the range parameters: start, stop exclusive, step:
np.arange(5, 21, 2)
array([ 5, 7, 9, 11, 13, 15, 17, 19])
### 2 Exercise: Create an array of values from 10 to 50 with a step of
### 5 using `arange()`. What is the length of the resulting array?
### Produce the same output as the cell below.
### Your code starts here:
### Your code ends here.
[10 15 20 25 30 35 40 45 50]
9
3.1.3.3. Other np Functions#
Besides array() and arange(), NumPy has functions that create arrays of a given shape or spacing. Their main parameters are:
np.zeros(shape, dtype=float): an array filled with zerosnp.ones(shape, dtype=float): an array filled with onesnp.full(shape, fill_value, dtype=None): an array filled withfill_valuenp.linspace(start, stop, num=50, endpoint=True, dtype=None):numevenly spaced values fromstarttostopnp.eye(N, M=None, k=0, dtype=float): a 2-D array with ones on the diagonal
3.1.3.3.1. zeros(), ones(), and full()#
These functions initialize arrays of a specified shape filled with zeros, ones, or a constant value, respectively. Each takes the shape as its first argument, passed as an integer (1-D) or as a tuple or list (one number per dimension).
### zeros() function creates an array filled with zeros.
### You can specify the shape and data type of the array.
np.zeros((3, 4)) ### passing shape parameter with a tuple
### by default, the dtype is float64
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
np.zeros(5, dtype=int) ### passing shape parameter with an integer
array([0, 0, 0, 0, 0])
### ones() function creates an array filled with ones.
arr_ones = np.ones(3) ### vector array of 1's
arr_ones ### type float64 by default
array([1., 1., 1.])
arr_ones.dtype
dtype('float64')
arr_ints = np.ones([2,3], int) ### specify dtype to int
print(arr_ints)
print()
print(type(arr_ints)) ### check the type of arr_ints using the built-in type() function
print(arr_ints.dtype) ### check the np data type of arr_ints using the built-in dtype attribute
[[1 1 1]
[1 1 1]]
<class 'numpy.ndarray'>
int64
np.full((2, 3), 5) ### fill the shape (2x3) with 5
array([[5, 5, 5],
[5, 5, 5]])
### 3 Exercise: Create a 1-D NumPy array of length 5 filled with the
### value 5 using `full()`. Print the array and its data type.
### Your code starts here:
### Your code ends here.
[5 5 5 5 5]
int64
3.1.3.3.2. linspace()#
linspace( ) stands for linear space. linspace returns evenly spaced numbers over a specified interval. linspace() takes three main arguments: the start value, the stop value, and the number of elements to generate. Note that the stop parameter is inclusive.
### Create five evenly spaced values from 0 to 10 (stop is inclusive)
np.linspace(0, 10, 5)
array([ 0. , 2.5, 5. , 7.5, 10. ])
### eleven values from 0 to 1, a step of 0.1
arr = np.linspace(0, 1, 11)
print(arr)
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
3.1.3.3.3. eye()#
An identity matrix is a square matrix with 1s on the main diagonal and 0s everywhere else. It plays the same role in matrix multiplication that the number 1 plays in ordinary multiplication.
To create an identity matrix:
np.eye(4)
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
3.1.3.4. reshape()#
The reshape() function changes the shape of a NumPy array without altering its underlying data. It returns a new array (or a view of the original array if possible) with the specified new shape.
import numpy as np
arr = np.linspace(0, 11, 12, dtype=int)
print(arr, '\n')
arr.reshape(3, 4)
[ 0 1 2 3 4 5 6 7 8 9 10 11]
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
### create an array of 16 values with a list comprehension
arr = np.array([num for num in range(16)])
arr
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
### reshape into 4 rows and 4 columns
arr = arr.reshape(4, 4)
arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
### the same 16 values in 2 rows and 8 columns
arr.reshape(2, 8)
array([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 8, 9, 10, 11, 12, 13, 14, 15]])
### this will not work
# arr.reshape(5,5) ### ValueError: cannot reshape array of size 16 into shape (5,5)
arr_25 = np.arange(25) ### create an array of 25 values from 0 to 24
arr_25.reshape(5, 5) ### reshape it to 5 rows and 5 columns
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
arr_25.reshape(5, 5).shape ### check the shape of the reshaped array
(5, 5)
### reshape does not change the original object
arr_25.shape ### check the shape of the original array
(25,)
arr_25 ### still a 1-D array of 25 values
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24])
### 4 Exercise: Create an array with 24 elements using `np.arange()`.
### Reshape it into a 4x6 array, then reshape it again into a 2x12 array.
### Print the shape after each reshape operation.
### Your code starts here:
### Your code ends here.
Original shape: (24,)
After first reshape (4, 6): (4, 6)
After second reshape (2, 12): (2, 12)
Final array:
[[ 0 1 2 3 4 5 6 7 8 9 10 11]
[12 13 14 15 16 17 18 19 20 21 22 23]]
3.1.3.5. Combining and Reshaping Arrays#
reshape() changes the shape of one array. Four more tools rearrange an array or join several arrays into one:
arr.flatten()returns a 1-D copy of the values, read row by row.arr.Treturns the transpose: rows become columns and columns become rows.np.concatenate((a, b), axis=0)joins arrays along an axis they already have.np.stack((a, b), axis=0)joins arrays of the same shape along a new axis.
The examples use monthly sales for two stores, one row per store and one column per month.
sales = np.array([[120, 135, 150],
[ 90, 110, 105]]) ### 2 stores (rows) x 3 months (columns)
print(sales.flatten()) ### all 6 values in one row, read row by row
print()
print(sales.T) ### 3 months (rows) x 2 stores (columns)
[120 135 150 90 110 105]
[[120 90]
[135 110]
[150 105]]
flatten() always returns a copy, so changing the flattened array leaves sales unchanged. T is an attribute, so it takes no parentheses; np.transpose(sales) gives the same result.
np.concatenate() takes the arrays as one tuple or list. With axis=0 (the default), it adds rows, so the arrays must have the same number of columns. With axis=1, it adds columns, so they must have the same number of rows.
store_3 = np.array([[100, 95, 130]]) ### a third store: 1 row x 3 months
month_4 = np.array([[160],
[115]]) ### a fourth month for both stores: 2 rows x 1 column
print(np.concatenate((sales, store_3))) ### axis=0: add a row, shape (3, 3)
print()
print(np.concatenate((sales, month_4), axis=1)) ### axis=1: add a column, shape (2, 4)
[[120 135 150]
[ 90 110 105]
[100 95 130]]
[[120 135 150 160]
[ 90 110 105 115]]
np.stack() adds a dimension: stacking two 1-D arrays gives a 2-D array. With axis=0, each input becomes a row; with axis=1, each input becomes a column.
jan = np.array([120, 90]) ### January sales for the two stores
feb = np.array([135, 110]) ### February sales
print(np.stack((jan, feb))) ### axis=0: one row per month, shape (2, 2)
print()
print(np.stack((jan, feb), axis=1)) ### axis=1: one column per month, one row per store
[[120 90]
[135 110]]
[[120 135]
[ 90 110]]
### 5 Exercise: Two warehouses report units shipped over four weeks.
### - Stack wh_a and wh_b into a 2-D array with one row per warehouse; print it
### - Print its transpose (one row per week)
### - Add wh_c as a third row with np.concatenate(); print the new shape
### - Print the flattened 3-warehouse array
wh_a = np.array([40, 42, 38, 45])
wh_b = np.array([30, 35, 33, 31])
wh_c = np.array([[25, 28, 27, 30]]) ### already 2-D: 1 row x 4 weeks
### Your code starts here:
### Your code ends here.
[[40 42 38 45]
[30 35 33 31]]
[[40 30]
[42 35]
[38 33]
[45 31]]
(3, 4)
[40 42 38 45 30 35 33 31 25 28 27 30]
3.1.4. Array Attributes#
Commonly used NumPy array attributes include:
dtype: shows data type of elements (e.g., float64, int32, complex128)ndim: shows number of dimensions (rank)shape: shows a tuple of lengths per axis (assignable to reshape if sizes match)size: shows the total number of elements in the arrayitemsize: shows the size in bytes of each elementnbytes: shows the total memory (in bytes) the array occupies (size × itemsize)T: returns the transposed array (an attribute, not a method — no parentheses needed)
3.1.4.1. dtype#
The dtype property in NumPy is an attribute of a NumPy array (ndarray) that displays the data type of its elements. You can get the data type of the object in the array.
Note that in the example below, i4 means a 4-byte signed integer (int32). Because 4 = 4 bytes, 4 bytes × 8 bits = 32 bits.
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)
[1 2 3 4]
int32
### without specifying the dtype, NumPy will infer the data type
### based on the input values. In this case, it will default to `int64` on most systems.
arr = np.array([1, 2, 3, 4])
print(arr)
print(arr.dtype)
[1 2 3 4]
int64
### Create an array with a specific data type
np.array([1, 2, 3, 4], dtype=np.float32)
array([1., 2., 3., 4.], dtype=float32)
Common dtype options:
int, int32, int64 # integer types
float, float32, float64 # floating-point types
complex, complex64 # complex numbers
bool # boolean
str, 'U10' # string (U10 = Unicode string, max 10 chars)
num1 = np.arange(5, dtype=int) # [0 1 2 3 4] as integers
num2 = np.arange(5, dtype=float) # [0. 1. 2. 3. 4.] as floats
num3 = np.zeros(5, dtype=int) # [0 0 0 0 0]
num4 = np.ones((3, 4), dtype=float) # 3x4 array of 1.0s
print(num1.dtype)
print(num2.dtype)
print(num3.dtype)
print(num4.dtype)
print('\n',num1)
print(num2)
print(num3)
print(num4)
int64
float64
int64
float64
[0 1 2 3 4]
[0. 1. 2. 3. 4.]
[0 0 0 0 0]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
3.1.4.1.1. Understanding String Dtypes#
When NumPy creates an array of strings, it automatically determines the data type based on the longest string in the array. The notation <U6 means:
U= Unicode string6= Maximum length of 6 characters
For example, if you create an array with the strings 'apple', 'banana', and 'cherry', the longest string is 6 characters, so the dtype becomes <U6. This ensures all strings fit within the allocated space.
arr_string1 = np.array(['apple', 'banana', 'cherry'])
arr_string2 = np.array(['apple', 'banana', 'cherry', 'date', 'elderberry'])
print(arr_string1.dtype) ### U means Unicode string, 6 is the longest string length
print(arr_string2.dtype)
print("\n'U6' means: Unicode string with maximum length of 6 characters (cherry)")
<U6
<U10
'U6' means: Unicode string with maximum length of 6 characters (cherry)
3.1.4.2. ndim#
The ndim attribute represents the number of dimensions (or axes) of the array.
arr = np.arange(1, 6)
print(arr)
arr.ndim
[1 2 3 4 5]
1
arr_25 = np.arange(25)
arr_55 = arr_25.reshape(5, 5)
arr_55.ndim
2
### 6 Exercise: Use `arange()` and `reshape()` to create arrays of different
### dimensions and check their ndim attribute:
# - Create a 1-D array with 5 elements
# - Create a 2-D array with shape (3, 4)
# - Create a 3-D array with shape (2, 3, 2)
# - Print the ndim for each array
### Your code starts here:
### Your code ends here.
1-D ndim: 1
2-D ndim: 2
3-D ndim: 3
3.1.4.3. shape#
The shape attribute returns a tuple of integers, one per dimension, giving the number of elements along that dimension. The shape of a 1-D array has one number followed by a comma, such as (5,): the comma marks a tuple with one element.
arr_2d = np.array([ [1, 2, 3], [4, 5, 6] ])
arr_2d.shape
(2, 3)
### np.arange creating a 1-D array
arr_vec = np.arange(1, 10, 2)
print("the vector:", arr_vec)
print("the shape:", arr_vec.shape)
the vector: [1 3 5 7 9]
the shape: (5,)
arr_25 = np.arange(25)
arr_25.shape
(25,)
### 7 Exercise: Examine the shape attribute of different arrays:
### - Create a 1-D array with 10 elements and print its shape
### - Create a 2-D array with 3 rows and 5 columns, print its shape
### - Reshape a 1-D array of 20 elements into a 4x5 array and print the shape before and after
### Your code starts here:
### Your code ends here.
1-D array shape: (10,)
2-D array shape: (3, 5)
Before reshape - shape: (20,)
After reshape - shape: (4, 5)
3.1.4.4. size#
The size attribute returns the total number of elements in an array. For a 2-D array, this is the number of rows times the number of columns.
arr_2d = np.array([[1, 2, 3],
[4, 5, 6]])
print("shape:", arr_2d.shape)
print("size:", arr_2d.size)
shape: (2, 3)
size: 6
The itemsize, nbytes, and T attributes work the same way. Each value in arr_2d is a 64-bit (8-byte) integer, so its 6 values take 48 bytes, and T swaps rows and columns:
print("itemsize:", arr_2d.itemsize)
print("nbytes:", arr_2d.nbytes)
print("transposed:")
print(arr_2d.T)
itemsize: 8
nbytes: 48
transposed:
[[1 4]
[2 5]
[3 6]]
3.1.5. Indexing and Selection#
Just like Python lists, square brackets [ ] are used for selecting the elements or groups of elements from an array:
Accessing individual elements of a list (indexing).
Selecting sub-sequences (slicing with parameters: start, stop exclusive, and step). Note that slicing returns a numpy array.
Negative indexing: begins with -1 from the end of the sequence.
arr = np.arange(0,10) ### creating sample array
print(arr) ### better looking of array output
arr ### array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print()
print("Shape:", arr.shape) ### shape of the array
print("Dim :", arr.ndim) ### dimension of the array
[0 1 2 3 4 5 6 7 8 9]
Shape: (10,)
Dim : 1
print(arr[1]) ### indexing
print(arr[0:3]) ### slicing
print(arr[0:5:2]) ### slicing with step size
print(arr[-1]) ### negative indexing
print(arr[-3:-1]) ### slicing with negative indices
1
[0 1 2]
[0 2 4]
9
[7 8]
### 8 Exercise: Create an array from 0 to 9 using `np.arange()`.
### Then perform the following operations:
### - Get the element at index 5
### - Get elements from index 2 to 6 (exclusive)
### - Get every second element starting from index 1
### - Get the last 3 elements using negative indexing
### Your code starts here:
### Your code ends here.
Element at index 5: 5
Elements from index 2 to 6: [2 3 4 5]
Every second element from index 1: [1 3 5 7 9]
Last 3 elements: [7 8 9]
3.1.5.1. Indexing/Slicing 2-D Arrays#
To access a 2-D array (matrices), use the syntax array[row_index, column_index]. The general format is arr[row][col] or arr[row, col].
### creating a 2-d array
arr_2d = np.array(([5,10,15],[20,25,30],[35,40,45]))
arr_2d
array([[ 5, 10, 15],
[20, 25, 30],
[35, 40, 45]])
### 0-based indexing; 1st row. It will return the first row of the
### 2D array, which is [5, 10, 15].
arr_2d[0]
array([ 5, 10, 15])
### 0-based indexing; 2nd row, 3rd column. It will return the
### element at the second row and third column of the 2D array, which is 30.
arr_2d[1, 2]
np.int64(30)
### 2D array slicing
### shape (2,2) from top right corner
arr_2d[:2, 1:]
array([[10, 15],
[25, 30]])
### 9 Exercise: Create a 3x4 2-D array containing the values 1 through 12. Then:
### - Extract the first and last rows
### - Extract the middle two columns
### - Extract the 2x2 subarray in the top two rows of the middle two columns
### Your code starts here:
### Your code ends here.
First and last rows:
[[ 1 2 3 4]
[ 9 10 11 12]]
Middle two columns:
[[ 2 3]
[ 6 7]
[10 11]]
Top-middle 2x2 subarray:
[[2 3]
[6 7]]