CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Introduction to NumPy
Complete chapter notes based on the supplied 28-page textbook PDF. Includes clear explanations, syntax, worked examples, expected outputs, practical tips, all textbook exercise questions with solutions, and the Iris flower dataset case study.
Learning objectives
After studying this chapter, students should be able to:
- Explain NumPy and the purpose of arrays in scientific computing.
- Create one-dimensional and two-dimensional NumPy arrays.
- Read array attributes such as dimensions, shape, size, data type and item size.
- Access array elements using indexing and extract portions using slicing.
- Perform arithmetic, transpose and sorting operations.
- Concatenate, reshape and split arrays.
- Calculate maximum, minimum, sum, mean and standard deviation.
- Load data from text/CSV files and save NumPy arrays to disk.
6.1 Introduction
NumPy stands for Numerical Python. It is a Python package used for data analysis and scientific computing. NumPy provides a powerful multidimensional array object and a large collection of functions and tools for working with arrays.
Why is NumPy useful?
- Its n-dimensional array helps process numerical data efficiently.
- It provides functions to create, manipulate and transform arrays.
- It can be used with other Python packages.
- It provides tools for integration with programming languages such as C and C++.
Installing NumPy
Open Command Prompt or a terminal and execute:
pip install numpy
In a Jupyter Notebook, the command may be run in a code cell using:
%pip install numpy
Importing NumPy
import numpy as np
np is an alias (short name) for the NumPy module. The textbook uses this common convention throughout its examples.
numpy in lowercase. After importing it as np, NumPy functions are called using the np. prefix, for example np.array().6.2 Array
An array is a data structure used to store multiple values using a single identifier (variable name). It is an ordered collection of elements. In the array discussed in this chapter, all elements have the same data type, and each element is accessed using its index (position).
Important characteristics of an array
- Same data type: All elements have the same data type, although their values may be different.
- Contiguous memory: Array elements are stored in contiguous memory locations. This supports efficient array operations.
- Index-based access: Each element is identified by the array name and its index.
Example of zero-based indexing
Values: [10, 9, 99, 71, 90] Index: 0 1 2 3 4
The first element has index 0, the second has index 1, and the fifth has index 4. This is called zero-based indexing, just like Python lists.
Contiguous memory allocation
Contiguous memory allocation means that the elements of an array are stored in adjacent memory locations in a continuous block. This layout allows the computer to locate elements efficiently.
6.3 NumPy Array
NumPy arrays are used to store numerical data, vectors and matrices. NumPy provides many built-in routines for creating, manipulating and transforming arrays.
The NumPy array is officially called ndarray (n-dimensional array), but it is commonly called an array. Unless otherwise specified, the word array in this chapter means a NumPy ndarray.
6.3.1 Difference Between List and Array
| Python List | NumPy Array |
|---|---|
Can contain elements of different data types, for example [1, 3.4, "hello", "a@"]. | All elements have the same data type. For example, an array may contain floats: [1.2, 5.4, 2.7]. |
| Elements are not necessarily stored contiguously in memory. | Elements are stored in contiguous memory locations, supporting faster numerical operations. |
| Does not perform mathematical operations element by element in the same way as NumPy arrays. | Supports element-wise operations. For example, A1 / 3 divides every element by 3. |
| Stores object/type information for individual elements, which can require more memory. | Uses a common data type for its elements and is generally more memory-efficient for numerical data. |
| Part of core Python. | Provided by the NumPy library. |
List operation versus array operation
# Python list numbers = [10, 20, 30] print(numbers * 2) # Output: [10, 20, 30, 10, 20, 30] # NumPy array import numpy as np values = np.array([10, 20, 30]) print(values * 2) # Output: [20 40 60]
6.3.2 Creation of NumPy Arrays from List
First import NumPy. The np.array() function converts a Python list or nested lists into a NumPy array.
Basic syntax
import numpy as np array_name = np.array(list_name)
Example: Create a 1-D array
import numpy as np array1 = np.array([10, 20, 30]) print(array1)
[10 20 30]
A 1-D array contains elements arranged in one dimension (a single sequence).
Automatic data-type conversion (type promotion)
array2 = np.array([5, -7.4, 'a', 7.2]) print(array2)
['5' '-7.4' 'a' '7.2']
Since the input list contains a string, NumPy converts the numeric values to strings so that all array elements have one common data type. The textbook output shows dtype='<U32'; U32 indicates a Unicode string type.
Creating a 2-D array using nested lists
A 2-D array has rows and columns. It is created by passing a nested list (a list whose elements are themselves lists) to np.array().
array3 = np.array([
[2.4, 3],
[4.91, 7],
[0, -1]
])
print(array3)[[ 2.4 3. ] [ 4.91 7. ] [ 0. -1. ]]
The integer values are promoted to floating-point values because the array contains decimal values.
np.array(). Incorrect: np.array(1, 2, 3, 4). Correct: np.array([1, 2, 3, 4]).1-D and 2-D arrays at a glance
a = np.array([10, 20, 30])
Shape: (3,)
b = np.array([[1, 2],
[3, 4]])Shape: (2, 2)
6.3.3 Attributes of NumPy Array
Array attributes provide information about the structure and storage of a NumPy array. The chapter explains five important attributes.
1. ndarray.ndim – Number of dimensions
Returns the number of dimensions of the array as an integer. NumPy also calls dimensions axes; the number of axes is called the array's rank. In a 2-D array, axis 0 is the row axis and axis 1 is the column axis.
array1 = np.array([10, 20, 30]) array3 = np.array([[2.4, 3], [4.91, 7], [0, -1]]) print(array1.ndim) # 1 print(array3.ndim) # 2
2. ndarray.shape – Size along each dimension
Returns a tuple containing the size of the array along each dimension. For a 2-D array, the tuple is (number of rows, number of columns).
print(array1.shape) # (3,) print(array3.shape) # (3, 2)
(3, 2) means 3 rows and 2 columns. The comma in (3,) indicates a one-element tuple for a 1-D array.
3. ndarray.size – Total number of elements
Returns the total number of elements. For a 2-D array, it is rows × columns.
print(array1.size) # 3 print(array3.size) # 6
4. ndarray.dtype – Data type of elements
Returns the common data type of all elements in the array. Examples include int32, int64, float32, float64 and Unicode string types such as U32.
print(array1.dtype) print(array3.dtype)
Exact integer width can depend on the platform and NumPy build. The textbook examples show int32 and float64.
5. ndarray.itemsize – Bytes used by each element
Returns the number of bytes occupied by one array element. Since 8 bits = 1 byte:
- 32-bit value: 32 ÷ 8 = 4 bytes.
- 64-bit value: 64 ÷ 8 = 8 bytes.
print(array1.itemsize) # textbook example: 4 bytes for int32 print(array3.itemsize) # textbook example: 8 bytes for float64
Complete attribute example
a = np.array([[1, 2, 3], [4, 5, 6]])
print("Dimensions:", a.ndim)
print("Shape:", a.shape)
print("Total elements:", a.size)
print("Data type:", a.dtype)
print("Bytes per element:", a.itemsize)Dimensions: 2 Shape: (2, 3) Total elements: 6 Data type: int64 # may vary by system Bytes per element: 8 # for int64
6.3.4 Other Ways of Creating NumPy Arrays
1. Specify data type using dtype
The dtype argument specifies the data type to be used while creating the array. Values are converted to the requested type when conversion is possible.
array4 = np.array([[1, 2], [3, 4]], dtype=float) print(array4)
[[1. 2.] [3. 4.]]
2. np.zeros() – Create an array filled with zeros
Syntax:
np.zeros(shape, dtype=float)
The shape is supplied as a tuple. By default, the elements are floating-point zeros.
array5 = np.zeros((3, 4)) print(array5)
[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]
3. np.ones() – Create an array filled with ones
Syntax:
np.ones(shape, dtype=float)
array6 = np.ones((3, 2)) print(array6)
[[1. 1.] [1. 1.] [1. 1.]]
4. np.arange() – Create values in a sequence
np.arange() is similar to Python's range(). It creates evenly spaced values using a start, stop and step.
- start: first value (included); defaults to 0 if omitted.
- stop: ending boundary (excluded).
- step: difference between consecutive values; defaults to 1.
a = np.arange(6) print(a) # [0 1 2 3 4 5] b = np.arange(-2, 24, 4) print(b) # [-2 2 6 10 14 18 22]
np.arange(-2, 24, 4) stops at 22 because the next value, 26, would exceed the stop boundary.Quick comparison
| Function | Purpose | Example |
|---|---|---|
np.array() | Convert list/nested list to array | np.array([1,2,3]) |
np.zeros() | Fill with zeros | np.zeros((2,3)) |
np.ones() | Fill with ones | np.ones((2,3)) |
np.arange() | Generate a sequence | np.arange(1,10,2) |
6.4 Indexing and Slicing – 6.4.1 Indexing
Indexing means accessing a particular element using its position. NumPy uses zero-based indexing.
Indexing a 1-D array
a = np.array([10, 20, 30, 40, 50]) print(a[0]) # 10: first element print(a[2]) # 30: third element print(a[-1]) # 50: last element
Indexing a 2-D array
For a 2-D array, use two indexes: the first identifies the row and the second identifies the column.
| Student | Maths (col 0) | English (col 1) | Science (col 2) |
|---|---|---|---|
| Ramesh (row 0) | 78 | 67 | 56 |
| Vedika (row 1) | 76 | 75 | 47 |
| Harun (row 2) | 84 | 59 | 60 |
| Prasad (row 3) | 67 | 72 | 54 |
marks = np.array([
[78, 67, 56],
[76, 75, 47],
[84, 59, 60],
[67, 72, 54]
])
print(marks[0, 2]) # 56: Ramesh's Science marks
print(marks[3, 1]) # 72: Prasad's English marks
marks[3,1] means fourth row, second column because indexing begins at zero.
marks[0,4] is invalid. It produces an IndexError because column index 4 does not exist.6.4.2 Slicing
Slicing extracts a part of an array. It uses a start index and an end index. The start is included, but the end is excluded.
Slicing a 1-D array
a = np.array([-2, 2, 6, 10, 14, 18, 22]) print(a[3:5]) # [10 14] print(a[::-1]) # [22 18 14 10 6 2 -2]
a[3:5] selects indexes 3 and 4, not index 5. a[::-1] reverses the array using a step of -1.
Slicing a 2-D array
For a 2-D array, the syntax is array_name[row_slice, column_slice].
array9 = np.array([
[-7, 0, 10, 20],
[-5, 1, 40, 200],
[-1, 1, 4, 30]
])
# All elements in the third column
print(array9[0:3, 2])
# [10 40 4]
# Second and third rows, first and second columns
print(array9[1:3, 0:2])
# [[-5 1]
# [-1 1]]
# All rows, third column
print(array9[:, 2])
# [10 40 4]
Meaning of colon (:)
:by itself means select all indexes along that dimension.1:3means indexes 1 and 2 (end 3 excluded).0:3, 2means rows 0, 1 and 2 from column index 2.::-1means traverse in reverse order.
6.5 Operations on Arrays
After creating an array, we can access its elements and perform different operations. The chapter covers arithmetic operations, transpose and sorting.
6.5.1 Arithmetic Operations
NumPy performs arithmetic operations on corresponding elements of arrays. This is called element-wise operation.
Consider the two arrays:
array1 = np.array([[3, 6], [4, 2]]) array2 = np.array([[10, 20], [15, 12]])
Addition (+)
print(array1 + array2)
[[13 26] [19 14]]
Subtraction (-)
print(array1 - array2)
[[ -7 -14] [-11 -10]]
Element-wise multiplication (*)
print(array1 * array2)
[[30 120] [60 24]]
Matrix multiplication (@)
The @ operator performs matrix multiplication, which is different from element-wise multiplication.
print(array1 @ array2)
[[120 132] [ 70 104]]
Exponentiation (**)
print(array1 ** 3)
[[27 216] [64 8]]
Division (/)
print(array2 / array1)
[[3.33333333 3.33333333] [3.75 6. ]]
Remainder / Modulo (%)
print(array2 % array1)
[[1 2] [3 0]]
array1.shape must equal array2.shape. NumPy also supports broadcasting in compatible shapes, but that is beyond the basic rule used in this chapter.Element-wise vs matrix multiplication
| Operator | Operation | Example meaning |
|---|---|---|
* | Element-wise multiplication | Multiply values at matching positions. |
@ | Matrix multiplication | Multiply rows of the first matrix by columns of the second matrix and add products. |
6.5.2 Transpose
Transpose changes rows into columns and columns into rows. It is represented by the transpose() method or the .T attribute.
array3 = np.array([
[10, -7, 0, 20],
[-5, 1, 200, 40],
[30, 1, -1, 4]
])
print(array3.transpose())[[ 10 -5 30] [ -7 1 1] [ 0 200 -1] [ 20 40 4]]
The original array remains unchanged when transpose() returns the transposed result and that result is not assigned back.
6.5.3 Sorting
Sorting arranges elements in ascending or descending order. NumPy's sort() function sorts in ascending order by default.
Sorting a 1-D array
a = np.array([1, 0, 2, -3, 6, 8, 4, 7]) a.sort() print(a)
[-3 0 1 2 4 6 7 8]
Sorting a 2-D array row-wise (axis=1)
By default, sorting is performed along axis=1, meaning each row is sorted independently.
a = np.array([
[10, -7, 0, 20],
[-5, 1, 200, 40],
[30, 1, -1, 4]
])
a.sort()
print(a)[[ -7 0 10 20] [ -5 1 40 200] [ -1 1 4 30]]
Sorting a 2-D array column-wise (axis=0)
axis=0 sorts the values within each column.
b = np.array([
[10, -7, 0, 20],
[-5, 1, 200, 40],
[30, 1, -1, 4]
])
b.sort(axis=0)
print(b)[[ -5 -7 -1 4] [ 10 1 0 20] [ 30 1 200 40]]
axis=0 refers to the row direction (values are compared down columns); axis=1 refers to the column direction (values are sorted across each row).6.6 Concatenating Arrays
Concatenation means joining two or more arrays. In 1-D arrays, concatenation appends one sequence after another. For 2-D arrays, they can be joined row-wise or column-wise using np.concatenate().
axis=0: join vertically (add rows).axis=1: join horizontally (add columns).
Textbook Example 6.8
array1 = np.array([[10, 20], [-30, 40]]) array2 = np.zeros((2, 3), dtype=array1.dtype) print(np.concatenate((array1, array2), axis=1))
[[ 10 20 0 0 0] [-30 40 0 0 0]]
The result has 2 rows and 5 columns. The arrays have the same number of rows, so horizontal concatenation is valid.
Why can concatenation produce an error?
All dimensions must match except the dimension along which the arrays are joined. In the example, joining along axis=0 fails because the arrays have 2 and 3 columns respectively.
# Invalid for these shapes: np.concatenate((array1, array2), axis=0) # ValueError: dimensions other than concatenation axis # must match exactly
6.7 Reshaping Arrays
Reshaping changes the arrangement (shape) of an array without changing the total number of elements. Use reshape().
Textbook Example 6.9
array3 = np.arange(10, 22) print(array3) # [10 11 12 13 14 15 16 17 18 19 20 21] print(array3.reshape(3, 4)) print(array3.reshape(2, 6))
[[10 11 12 13] [14 15 16 17] [18 19 20 21]] [[10 11 12 13 14 15] [16 17 18 19 20 21]]
There are 12 elements, so valid reshapes include 3×4, 2×6, 4×3, 6×2 and 1×12.
6.8 Splitting Arrays
Splitting divides one array into two or more smaller sub-arrays. NumPy uses np.split(). You can specify split positions or the number of equal parts.
indices_or_sectionsmay be a sequence of split indexes or an integer specifying the number of equal sections.- Default
axis=0splits along rows. axis=1splits along columns.
Split by row indexes – textbook example
array4 = np.array([
[10, -7, 0, 20],
[-5, 1, 200, 40],
[30, 1, -1, 4],
[1, 2, 0, 4],
[0, 1, 0, 2]
])
first, second, third = np.split(array4, [1, 3])
print(first)
print(second)
print(third)[[10 -7 0 20]] [[ -5 1 200 40] [ 30 1 -1 4]] [[1 2 0 4] [0 1 0 2]]
Split indexes [1, 3] create sections before row index 1, between indexes 1 and 3, and after index 3.
Split by columns
firstc, secondc, thirdc = np.split(array4, [1, 2], axis=1) # firstc contains column 0 # secondc contains column 1 # thirdc contains columns 2 and 3
Split into equal parts
firsthalf, secondhalf = np.split(array4, 2, axis=1)
The number of sections must divide the selected axis evenly when using np.split(). If equal division is not possible, an error occurs. np.array_split() is a different function that can make unequal-sized sections, but it is not the function taught in this section.
6.9 Statistical Operations on Arrays
NumPy provides statistical functions that can be applied to arrays. These descriptive-statistics operations summarise data, as introduced in the previous chapter.
Consider the following arrays from the textbook:
arrayA = np.array([1, 0, 2, -3, 6, 8, 4, 7]) arrayB = np.array([[3, 6], [4, 2]])
1. max() – Maximum value
print(arrayA.max()) # 8 print(arrayB.max()) # 6 print(arrayB.max(axis=1)) # [6 4] print(arrayB.max(axis=0)) # [4 6]
2. min() – Minimum value
print(arrayA.min()) # -3 print(arrayB.min()) # 2 print(arrayB.min(axis=0)) # [3 2]
3. sum() – Sum of elements
print(arrayA.sum()) # 25 print(arrayB.sum()) # 15 print(arrayB.sum(axis=1)) # [9 6]
4. mean() – Average
print(arrayA.mean()) # 3.125 print(arrayB.mean()) # 3.75 print(arrayB.mean(axis=0)) # [3.5 4. ] print(arrayB.mean(axis=1)) # [4.5 3. ]
5. std() – Standard deviation
print(arrayA.std()) # approximately 3.55097 print(arrayB.std()) # approximately 1.47902 print(arrayB.std(axis=0)) # [0.5 2. ] print(arrayB.std(axis=1)) # [1.5 1. ]
Understanding axis in statistical operations
For arrayB = [[3, 6], [4, 2]]:
axis=1calculates one result for each row: row-wise.axis=0calculates one result for each column: column-wise.- Without an axis, the operation is applied to all elements.
| Expression | Meaning | Output |
|---|---|---|
arrayB.sum() | Sum all values | 15 |
arrayB.sum(axis=1) | Sum each row | [9, 6] |
arrayB.sum(axis=0) | Sum each column | [7, 8] |
max(), min(), sum(), mean() and std(), and practise their outputs with and without the axis argument.6.10 Loading Arrays from Files
Sometimes data is already stored in a text file and must be loaded into a NumPy array for processing. NumPy provides two important functions:
np.loadtxt()np.genfromtxt()
A commonly used text-file format is CSV (Comma-Separated Values). A CSV file stores tabular data in text form, with values separated by commas. The textbook notes that each row should contain the same number of values when loading a regular table into an array.
Example data file: data.txt
RollNo,Marks1,Marks2,Marks3 1,36,18,57 2,22,23,45 3,43,51,37 4,41,40,60 5,13,18,27
Assume the file is stored at C:/NCERT/data.txt. Replace this path with the actual location of your file when running the example.
6.10.1 Using NumPy loadtxt()
np.loadtxt() loads numerical data from a text file. It is suitable when the data is clean and consistently formatted.
Syntax
np.loadtxt(
fname,
skiprows=0,
delimiter=None,
dtype=float,
unpack=False
)
Load the complete numeric table
studentdata = np.loadtxt(
'C:/NCERT/data.txt',
skiprows=1,
delimiter=',',
dtype=int
)
print(studentdata)[[ 1 36 18 57] [ 2 22 23 45] [ 3 43 51 37] [ 4 41 40 60] [ 5 13 18 27]]
Important parameters
| Parameter | Purpose |
|---|---|
fname | File name or complete file path. |
skiprows=1 | Skips the first row, which in this example contains column headings. |
delimiter=',' | Specifies that values are separated by commas. Other separators can include semicolon, tab or space. |
dtype=int | Creates an integer array. The textbook notes that the default dtype is float. |
unpack=False | Default setting. Data is returned in its normal row/column arrangement. |
unpack=True | Returns the transposed arrangement, making columns available as separate arrays when unpacked. |
Import rows into separate arrays
stud1, stud2, stud3, stud4, stud5 = np.loadtxt(
'C:/NCERT/data.txt',
skiprows=1,
delimiter=',',
dtype=int
)
print(stud1)
# [ 1 36 18 57]
Import columns into separate arrays using unpack=True
rollno, mks1, mks2, mks3 = np.loadtxt(
'C:/NCERT/data.txt',
skiprows=1,
delimiter=',',
unpack=True,
dtype=int
)
print(rollno) # [1 2 3 4 5]
print(mks1) # [36 22 43 41 13]
print(mks2) # [18 23 51 40 18]
print(mks3) # [57 45 37 60]
unpack=True transposes the loaded data. It is useful when each column needs to be assigned to a separate variable.6.10.2 Using NumPy genfromtxt()
np.genfromtxt() also loads data from text files. Compared with loadtxt(), it can handle missing values and non-numeric entries in numeric columns.
Example file: dataMissing.txt
RollNo,Marks1,Marks2,Marks3 1,36,18,57 2,ab,23,45 3,43,51, 4,41,40,60 5,13,18,27
Here, the value ab is non-numeric and the third record has a missing Marks3 value.
Load data with missing values
dataarray = np.genfromtxt(
'C:/NCERT/dataMissing.txt',
skip_header=1,
delimiter=','
)
print(dataarray)[[ 1. 36. 18. 57.] [ 2. nan 23. 45.] [ 3. 43. 51. nan] [ 4. 41. 40. 60.] [ 5. 13. 18. 27.]]
nan means “Not a Number”. The function represents missing or non-numeric values in numeric columns as nan by default.
Replace missing/non-numeric values using filling_values
dataarray = np.genfromtxt(
'C:/NCERT/dataMissing.txt',
skip_header=1,
delimiter=',',
filling_values=-999,
dtype=int
)
print(dataarray)[[ 1 36 18 57] [ 2 -999 23 45] [ 3 43 51 -999] [ 4 41 40 60] [ 5 13 18 27]]
In this example, -999 is used as a special marker for missing or invalid values. The textbook also notes that when integer dtype is specified, invalid/missing numeric values may be represented by -1 if no other fill value is supplied.
Textbook activities
- Activity 6.1: To load a file including its header row, use the relevant header-skipping setting. For example,
skip_header=0does not skip the first line; however, a header containing text should not be treated as numeric data unless names/dtype handling is configured appropriately. - Activity 6.2: Import data column-wise into multiple arrays by using the
unpack=Trueparameter, as demonstrated in theloadtxt()section.
6.11 Saving NumPy Arrays in Files on Disk
The np.savetxt() function saves a NumPy array to a text file. It can be used to store processed results for later use.
Syntax
np.savetxt(
filename,
array,
delimiter=' ',
fmt='%.18e'
)
Textbook Example 6.11
np.savetxt(
'C:/NCERT/testout.txt',
studentdata,
delimiter=',',
fmt='%i'
)
filename: destination file path.studentdata: array to be saved.delimiter=',': separates values with commas.fmt='%i': saves values using integer formatting.
The textbook notes that the default format is float. Use a suitable format specifier for the data being saved.
Chapter Summary
- An array stores multiple values of the same data type. Its elements are indexed and stored contiguously in memory.
- NumPy is a Python library for scientific computing and provides the n-dimensional
ndarrayobject. np.array()converts a list or nested list into a NumPy array.- Array attributes include
ndim,shape,size,dtypeanditemsize. np.zeros(),np.ones()andnp.arange()provide other ways to create arrays.- Indexing accesses an element; slicing extracts a portion of an array.
- Arithmetic operations are applied element-wise when array shapes are compatible.
transpose()exchanges rows and columns;sort()sorts array values.np.concatenate()joins arrays;reshape()changes shape without changing element count.np.split()divides an array into sub-arrays.max(),min(),sum(),mean()andstd()perform statistical operations.np.loadtxt()andnp.genfromtxt()load text-file data;np.savetxt()saves arrays.
Textbook Exercise – Solved Answers
The following answers cover the exercise questions printed on pages 113–115. Array creation statements are shown first so that later commands can be executed in the same Python session.
Question 1. What is NumPy? How to install it?
NumPy stands for Numerical Python. It is a Python package for numerical computing and data analysis. It provides an n-dimensional array and functions to manipulate and analyse arrays. Install it using:
pip install numpy
Question 2. What is an array and how is it different from a list? What is the built-in array class in NumPy?
An array is an ordered collection of elements of the same data type, stored under one variable name and accessed using indexes. Unlike a Python list, a NumPy array uses a common data type, supports element-wise numerical operations and is generally more efficient for numerical data. The NumPy array class is called ndarray.
Question 3. What do you understand by rank of an ndarray?
The rank of an ndarray is the number of dimensions (axes) of the array. A 1-D array has rank 1; a 2-D array has rank 2.
Question 4. Create the following NumPy arrays
First import NumPy:
import numpy as np
(a) 1-D array zeros with 10 zero elements
zeros = np.zeros(10, dtype=int) print(zeros)
[0 0 0 0 0 0 0 0 0 0]
(b) 1-D array vowels containing a, e, i, o, u
vowels = np.array(['a', 'e', 'i', 'o', 'u']) print(vowels)
(c) 2-D array ones, 2 rows × 5 columns, integer type
ones = np.ones((2, 5), dtype=int) print(ones)
[[1 1 1 1 1] [1 1 1 1 1]]
(d) 2-D array myarray1 using nested lists
myarray1 = np.array([
[2.7, -2, -19],
[0, 3.4, 99.9],
[10.6, 0, 13]
])
print(myarray1)
(e) 2-D array myarray2 using arange, 3 rows × 5 columns, start 4, step 4, float type
myarray2 = np.arange(4, 64, 4, dtype=float).reshape(3, 5) print(myarray2)
[[ 4. 8. 12. 16. 20.] [24. 28. 32. 36. 40.] [44. 48. 52. 56. 60.]]
Question 5. Write NumPy commands using arrays from Question 4
(a) Find dimensions, shape, size, dtype and itemsize
for name, arr in [
("zeros", zeros), ("vowels", vowels), ("ones", ones),
("myarray1", myarray1), ("myarray2", myarray2)
]:
print(name)
print("ndim:", arr.ndim)
print("shape:", arr.shape)
print("size:", arr.size)
print("dtype:", arr.dtype)
print("itemsize:", arr.itemsize)
(b) Reshape ones to one row containing all 10 elements
ones = ones.reshape(1, 10) print(ones)
(c) Display second and third elements of vowels
print(vowels[1:3])
['e' 'i']
(d) Display all elements in second and third rows of myarray1
print(myarray1[1:3, :])
(e) Display elements in first and second columns of myarray1
print(myarray1[:, 0:2])
(f) Display first-column elements of second and third rows
print(myarray1[1:3, 0])
(g) Reverse the vowels array
print(vowels[::-1])
['u' 'o' 'i' 'e' 'a']
Question 6. Arithmetic operations using arrays from Question 4
(a) Divide all elements of ones by 3
print(ones / 3)
(b) Add myarray1 and myarray2
print(myarray1 + myarray2)
(c) Subtract myarray1 from myarray2 and store the result
result_sub = myarray2 - myarray1 print(result_sub)
(d) Multiply myarray1 and myarray2 element-wise
result_mul = myarray1 * myarray2 print(result_mul)
(e) Matrix multiplication and store in myarray3
myarray1 and myarray2 have shape (3, 5). Matrix multiplication of a (3×5) matrix by another (3×5) matrix is not valid because the inner dimensions (5 and 3) do not match. This part of the printed exercise is inconsistent with its own array dimensions. To demonstrate a valid matrix multiplication, transpose the second array: myarray3 = myarray1 @ myarray2.T, which produces a 3×3 result. This is a mathematically valid correction for practice, not a change to the printed question.myarray3 = myarray1 @ myarray2.T print(myarray3)
(f) Divide myarray1 by myarray2
print(myarray1 / myarray2)
(g) Cube every element of myarray1 and divide the result by 2
print((myarray1 ** 3) / 2)
(h) Square root every element of myarray2, divide by 2 and round to 2 decimals
result = np.sqrt(myarray2) / 2 print(result.round(2))
Question 7. Transpose and sorting
(a) Find transpose of ones and myarray2
print(ones.transpose()) print(myarray2.transpose())
(b) Sort vowels in reverse order
print(np.sort(vowels)[::-1])
(c) Sort myarray1 so the lowest value of each column is in the first row
myarray1_sorted = np.sort(myarray1, axis=0) print(myarray1_sorted)
Question 8. Splitting and concatenation
(a) Split myarray2 column-wise into five arrays
myarray2A, myarray2B, myarray2C, myarray2D, myarray2E = np.split(
myarray2, 5, axis=1
)
print(myarray2A)
print(myarray2B)
print(myarray2C)
print(myarray2D)
print(myarray2E)
(b) Split zeros at indexes 2, 5, 7 and 8
zerosA, zerosB, zerosC, zerosD, zerosE = np.split(
zeros, [2, 5, 7, 8]
)
print(zerosA, zerosB, zerosC, zerosD, zerosE)
zerosA, zerosB, zerosC and zerosD (four variables), but four split positions create five resulting pieces. The correct unpacking therefore needs five variables, as shown above. If the exercise intended four output arrays, it should provide only three split positions.(c) Concatenate myarray2A, myarray2B and myarray2C into 3 rows × 3 columns
myarray2ABC = np.concatenate(
(myarray2A, myarray2B, myarray2C), axis=1
)
print(myarray2ABC)
Question 9. Create myarray4 with 14 rows and 3 columns
Start value = -1, step = 0.25. A 14×3 array needs 42 values. The following creates 42 values and reshapes them to the required dimensions:
myarray4 = np.arange(-1, 9.5, 0.25).reshape(14, 3) print(myarray4)
Split the array row-wise into 3 parts. Since 14 rows cannot be divided into three exactly equal integer-sized groups, np.split() cannot do this equally. The question says “3 equal parts”; use np.array_split() to create three nearly equal parts (5, 5 and 4 rows), or revise the number of rows to a multiple of 3 if exactly equal parts are required.
part1, part2, part3 = np.array_split(myarray4, 3, axis=0) print(part1) print(part2) print(part3)
np.split() requires equal division for an integer section count; np.array_split() permits unequal-sized sections.Question 10. Statistical operations on myarray4
(a) Sum of all elements
myarray4.sum()
(b) Sum row-wise
myarray4.sum(axis=1)
(c) Sum column-wise
myarray4.sum(axis=0)
(d) Maximum of all elements
myarray4.max()
(e) Minimum of all elements in each row
myarray4.min(axis=1)
(f) Mean of all elements in each row
myarray4.mean(axis=1)
(g) Standard deviation column-wise
myarray4.std(axis=0)
Case Study (Solved): Iris Flower Dataset
What is a dataset?
A dataset is a collection of data. It commonly corresponds to a database table or statistical data matrix. Each column represents a variable, and each row represents an item or observation. For example, a student dataset may contain height and weight for each student.
Open data is information released in a publicly accessible repository.
About the Iris flower dataset
The Iris dataset is also known as Fisher's Iris dataset. It was introduced by British statistician and biologist Ronald Fisher in 1936. The complete dataset contains 50 samples from each of three Iris species. Four features are measured in centimetres:
- Sepal length
- Sepal width
- Petal length
- Petal width
The three species are Iris setosa, Iris virginica and Iris versicolor. The textbook uses a smaller subset of 30 rows (10 samples for each species), and adds a numeric species column.
| Column | Description |
|---|---|
| Sepal length | Length of the sepal in cm |
| Sepal width | Width of the sepal in cm |
| Petal length | Length of the petal in cm |
| Petal width | Width of the petal in cm |
| Iris | Species name |
| Species No | Numeric code for species |
Prepare the Iris.txt file
The textbook instructs students to create a text file named Iris.txt using a text editor. It contains a header and comma-separated records. The full 30-record table appears on printed pages 115–117. A few initial rows are shown below to illustrate the format:
sepal length,sepal width,petal length,petal width,iris,Species No 5.1,3.5,1.4,0.2,Iris-setosa,1 4.9,3,1.4,0.2,Iris-setosa,1 4.7,3.2,1.3,0.2,Iris-setosa,1 4.6,3.1,1.5,0.2,Iris-setosa,1 5,3.6,1.4,0.2,Iris-setosa,1 ...
Save all 30 rows in the file before running the case-study program. The textbook identifies the UCI Machine Learning Repository as a source for the complete dataset.
Step-by-step solutions to the 15 case-study tasks
Step 1 – Load Iris.txt into a 2-D array called iris
import numpy as np
iris = np.genfromtxt(
'C:/NCERT/Iris.txt',
skip_header=1,
delimiter=',',
usecols=(0, 1, 2, 3, 5),
dtype=float
)
The usecols=(0, 1, 2, 3, 5) argument selects the four numeric measurements and the numeric species code, excluding the text species-name column. This is the executable way to obtain the numeric array required by the later calculations.
Step 2 – Drop the species-name column (concept)
The textbook's intended selection is to retain columns 0, 1, 2, 3 and 5. Since Step 1 already selects those columns using usecols, no further deletion is required. If a numeric array containing all six numeric-compatible columns were already available, the selection would be:
iris = iris[0:30, [0, 1, 2, 3, 5]]
dtype=float while the source file includes text values such as Iris-setosa in column 4. Converting that text column to float would fail. The usecols argument above skips the text column while loading and keeps the numeric columns required for the case study.Step 3 – Display shape, dimensions and size
print(iris.shape) # (30, 5) print(iris.ndim) # 2 print(iris.size) # 150
Step 4 – Split into three 2-D arrays
iris1, iris2, iris3 = np.split(iris, [10, 20], axis=0)
Step 5 – Print the three arrays
print("Iris 1:", iris1)
print("Iris 2:", iris2)
print("Iris 3:", iris3)
Each array contains 10 rows and 5 columns. The first 10 rows are setosa, the next 10 are versicolor in the supplied data, and the final 10 are virginica.
Step 6 – Create a header array
header = np.array([
"sepal length",
"sepal width",
"petal length",
"petal width",
"Species No"
])
Step 7 – Display the header
print(header)
Step 8 – Find maximum, minimum, mean and standard deviation for the whole dataset
iris_max = iris.max(axis=0)
iris_min = iris.min(axis=0)
iris_avg = iris.mean(axis=0).round(2)
iris_std = iris.std(axis=0).round(2)
print("Maximum:", iris_max)
print("Minimum:", iris_min)
print("Mean:", iris_avg)
print("Standard deviation:", iris_std)Maximum: [6.9 3.9 5.9 2.5 3. ] Minimum: [4.4 2.3 1.3 0.1 1. ] Mean: [5.68 3.03 3.61 1.22 2. ] Standard deviation: [0.76 0.35 1.65 0.82 0.82]
Step 9 – Find statistics for each species array
# Maximum iris1_max = iris1.max(axis=0) iris2_max = iris2.max(axis=0) iris3_max = iris3.max(axis=0) # Minimum iris1_min = iris1.min(axis=0) iris2_min = iris2.min(axis=0) iris3_min = iris3.min(axis=0) # Mean iris1_avg = iris1.mean(axis=0) iris2_avg = iris2.mean(axis=0) iris3_avg = iris3.mean(axis=0) # Standard deviation iris1_std = iris1.std(axis=0).round(2) iris2_std = iris2.std(axis=0).round(2) iris3_std = iris3.std(axis=0).round(2)
| Statistic | Iris 1 (setosa) | Iris 2 (versicolor in sample) | Iris 3 (virginica in sample) |
|---|---|---|---|
| Maximum | [5.4, 3.9, 1.7, 0.4, 1] | [6.2, 3.0, 4.6, 1.4, 2] | [6.9, 3.4, 5.9, 2.5, 3] |
| Minimum | [4.4, 2.9, 1.3, 0.1, 1] | [5.0, 2.3, 3.0, 1.0, 2] | [5.8, 2.5, 5.0, 1.9, 3] |
| Mean | [4.86, 3.31, 1.45, 0.22, 1] | [5.64, 2.73, 4.03, 1.23, 2] | [6.55, 3.04, 5.36, 2.20, 3] |
| Std. dev. | [0.28, 0.29, 0.10, 0.07, 0] | [0.36, 0.22, 0.47, 0.11, 0] | [0.34, 0.25, 0.28, 0.20, 0] |
Step 10 – Compare minimum values of each species with the whole dataset
# Compare minimum sepal length print(iris1_min[0] > iris_min[0]) # False print(iris2_min[0] > iris_min[0]) # True print(iris3_min[0] > iris_min[0]) # True
Repeat the same comparison for columns 1, 2 and 3 to fill the table:
| Feature | Iris setosa | Iris virginica (code 3) | Iris versicolor (code 2) |
|---|---|---|---|
| Sepal length | False | True | True |
| Sepal width | True | True | False |
| Petal length | False | True | True |
| Petal width | False | True | True |
Step 11 – Compare average sepal width of setosa and virginica
print(iris1_avg[1] > iris3_avg[1]) # True (3.31 > 3.04)
Step 12 – Compare average petal length of setosa and virginica
print(iris1_avg[2] > iris3_avg[2]) # False (1.45 is not greater than 5.36)
Step 13 – Compare average petal width of setosa and virginica
print(iris1_avg[3] > iris3_avg[3]) # False (0.22 is not greater than 2.20)
Step 14 – Save iris_avg in a comma-separated file
np.savetxt(
'C:/NCERT/IrisMeanValues.txt',
iris_avg,
delimiter=','
)
Step 15 – Save iris_max, iris_avg and iris_min in IrisStat.txt
np.savetxt(
'C:/NCERT/IrisStat.txt',
(iris_max, iris_avg, iris_min),
delimiter=','
)
Important Syntax and Examination Revision
Array creation
import numpy as np a = np.array([1, 2, 3]) b = np.array([[1, 2], [3, 4]]) np.zeros((rows, columns)) np.ones((rows, columns), dtype=int) np.arange(start, stop, step)
Array attributes
a.ndim # number of dimensions a.shape # size of each dimension a.size # total elements a.dtype # data type of elements a.itemsize # bytes per element
Indexing and slicing
a[index] b[row_index, column_index] a[start:end] a[::-1] b[:, column_index] b[row_start:row_end, col_start:col_end]
Operations
a + b a - b a * b # element-wise multiplication a @ b # matrix multiplication a / b a ** 2 a % b a.transpose() a.sort() a.sort(axis=0)
Array structure
np.concatenate((a, b), axis=0) np.concatenate((a, b), axis=1) a.reshape(rows, columns) np.split(a, sections, axis=0) np.split(a, indices, axis=1)
Statistics and files
a.max()
a.min()
a.sum()
a.mean()
a.std()
np.loadtxt('data.csv', delimiter=',', skiprows=1)
np.genfromtxt('data.csv', delimiter=',', skip_header=1)
np.savetxt('output.csv', a, delimiter=',', fmt='%i')
Important points to remember
- NumPy stands for Numerical Python.
- The NumPy array class is
ndarray. - Array indexes start from zero.
- In a 2-D array,
axis=0is the row axis andaxis=1is the column axis. shapegives rows and columns;sizegives total elements.dtypegives the common data type;itemsizegives bytes per element.np.arange()excludes its stop value.- In slicing, the ending index is excluded.
*is element-wise multiplication;@is matrix multiplication.- Reshaping cannot change the total number of elements.
- Concatenated arrays must match in all dimensions except the joining axis.
loadtxt()is intended for regular data;genfromtxt()can handle missing or invalid values.savetxt()saves an array to a text file.
TEXTBOOK SOLUTION
Step-by-step solved textbook exercises, derivations, and solutions.
Exercise Solutions Being Updated
Step-by-step verified exercise solutions are currently being uploaded.
MCQ
High-yield board questions, previous year questions (PYQs), and model answer keys.
Important Questions Being Compiled
Board blueprint and previous years' exam questions for this chapter will be live soon.