2.2 Array Creation & Manipulation
NumPy Array Creation & Manipulation
NumPy provides a powerful collection of functions for creating arrays and controlling their structure. Instead of manually entering every value, we can generate arrays containing sequences, zeros, ones, or evenly spaced values.
Once an array has been created, NumPy allows us to change its structure using operations such as reshape, flatten, and ravel.
- Creating arrays using
np.array() - Creating sequences using
np.arange() - Generating evenly spaced values using
np.linspace() - Creating arrays filled with zeros
- Creating arrays filled with ones
- Creating empty and identity arrays
- Specifying array shapes
- Reshaping arrays using
reshape() - Flattening multidimensional arrays
- Understanding
flatten()andravel() - Checking whether a reshape is possible
- Practical Data Science examples
1. Creating an Array with np.array()
The simplest way to create a NumPy array from existing Python data
is the np.array() function.
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
print(numbers)
Output:
[10 20 30 40 50]
A two-dimensional array can be created using nested lists.
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(matrix)
Output:
[[1 2 3]
[4 5 6]]
2. np.arange() — Creating Number Sequences
np.arange() creates a sequence of values within a
specified range.
Syntax
np.arange(start, stop, step)
| Parameter | Meaning |
|---|---|
start |
Starting value. Defaults to 0 when omitted. |
stop |
End boundary. Normally not included. |
step |
Difference between consecutive values. |
Example 1 — Basic Sequence
numbers = np.arange(1, 6)
print(numbers)
Output:
[1 2 3 4 5]
Example 2 — Using a Step
numbers = np.arange(0, 11, 2)
print(numbers)
Output:
[ 0 2 4 6 8 10]
Example 3 — Starting Value
numbers = np.arange(10, 20)
print(numbers)
Output:
[10 11 12 13 14 15 16 17 18 19]
3. Important Rule of np.arange()
The stop value is generally excluded.
numbers = np.arange(1, 5)
print(numbers)
Output:
[1 2 3 4]
Remember: start is included, stop is normally excluded.
4. Using a Negative Step
np.arange() can also generate decreasing sequences.
numbers = np.arange(10, 0, -2)
print(numbers)
Output:
[10 8 6 4 2]
5. np.linspace() — Evenly Spaced Values
np.linspace() generates a specified number of evenly
spaced values between two endpoints.
Syntax
np.linspace(start, stop, num)
| Parameter | Meaning |
|---|---|
start |
Starting value. |
stop |
Ending value. Included by default. |
num |
Number of values to generate. |
Example
values = np.linspace(0, 10, 5)
print(values)
Output:
[ 0. 2.5 5. 7.5 10. ]
Five evenly spaced values are generated from 0 to 10.
6. np.arange() vs np.linspace()
| Feature | arange() |
linspace() |
|---|---|---|
| Main idea | Specify the step. | Specify the number of values. |
| Stop value | Normally excluded. | Included by default. |
| Typical use | Integer-like sequences. | Evenly spaced numerical points. |
| Example |
np.arange(0, 10, 2)
|
np.linspace(0, 10, 6)
|
arange() asks:
"What should the step be?"
linspace() asks:
"How many values do I need?"
7. np.zeros() — Creating Zero-Filled Arrays
np.zeros() creates an array in which all elements are
initialized to zero.
1D Array
zeros = np.zeros(5)
print(zeros)
Output:
[0. 0. 0. 0. 0.]
By default, the result is usually a floating-point array.
2D Array
zeros = np.zeros((2, 3))
print(zeros)
Output:
[[0. 0. 0.]
[0. 0. 0.]]
8. Specifying dtype with np.zeros()
The data type can be explicitly specified.
zeros = np.zeros(
5,
dtype=int
)
print(zeros)
print(zeros.dtype)
Output:
[0 0 0 0 0]
int64
The exact default integer width can depend on the platform.
9. np.ones() — Creating One-Filled Arrays
np.ones() creates an array containing ones.
ones = np.ones(5)
print(ones)
Output:
[1. 1. 1. 1. 1.]
2D Example
ones = np.ones((3, 2))
print(ones)
Output:
[[1. 1.]
[1. 1.]
[1. 1.]]
10. np.full() — Filling with a Specific Value
np.full() creates an array with a specified shape and
fills every element with the same value.
data = np.full(
(2, 3),
7
)
print(data)
Output:
[[7 7 7]
[7 7 7]]
This is useful when an array needs an initial constant value other than zero or one.
11. np.empty()
np.empty() creates an array with the requested shape
without explicitly initializing its elements to a particular
value.
data = np.empty((2, 3))
print(data)
The values in an empty array should not be assumed to be zero. They contain whatever values happen to be present in the allocated memory until you assign values to the array.
np.empty() can be useful when you intend to populate
the array immediately and want to avoid unnecessary initialization.
12. np.eye() — Identity Matrix
np.eye() creates a 2D array with ones on the main
diagonal and zeros elsewhere.
identity = np.eye(3)
print(identity)
Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Identity matrices are widely used in linear algebra and numerical computing.
13. np.diag()
np.diag() can create a diagonal matrix from a
one-dimensional array.
data = np.array([10, 20, 30])
matrix = np.diag(data)
print(matrix)
Output:
[[10 0 0]
[ 0 20 0]
[ 0 0 30]]
14. Understanding Array Shape
The shape of an array describes how its elements are organized along its dimensions.
data = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(data.shape)
Output:
(2, 3)
This means:
- 2 rows
- 3 columns
- 6 total elements
15. reshape() — Changing Array Structure
The reshape() method changes the shape of an array
without changing its elements.
numbers = np.arange(1, 7)
matrix = numbers.reshape(2, 3)
print(matrix)
Output:
[[1 2 3]
[4 5 6]]
The original array contains 6 elements and the new shape also contains 6 positions.
16. The Fundamental reshape() Rule
The total number of elements must remain the same when reshaping.
numbers = np.arange(1, 13)
matrix = numbers.reshape(3, 4)
print(matrix)
The original array contains 12 elements:
12
The new shape also requires:
3 × 4 = 12
Number of elements before reshape = Number of elements after reshape
17. Invalid Reshape
Consider an array containing 6 elements:
numbers = np.arange(1, 7)
matrix = numbers.reshape(4, 2)
This fails because:
4 × 2 = 8
but the original array contains only 6 elements.
NumPy raises a ValueError.
18. Automatic Dimension with -1
NumPy can automatically calculate one dimension when
-1 is supplied to reshape().
numbers = np.arange(1, 13)
matrix = numbers.reshape(3, -1)
print(matrix)
Output:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
NumPy determines that the missing dimension must be 4.
Only one dimension should normally be specified as
-1; NumPy calculates that dimension from the
total number of elements.
19. Reshaping into Different Structures
numbers = np.arange(1, 13)
print(numbers.reshape(2, 6))
print(numbers.reshape(3, 4))
print(numbers.reshape(4, 3))
print(numbers.reshape(6, 2))
All of these are valid because every shape contains 12 elements.
20. flatten() — Converting to One Dimension
The flatten() method converts a multidimensional
array into a one-dimensional array.
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
flat = matrix.flatten()
print(flat)
Output:
[1 2 3 4 5 6]
The resulting array has one dimension.
21. Important Property of flatten()
flatten() returns a copy of the array data.
matrix = np.array([
[1, 2],
[3, 4]
])
flat = matrix.flatten()
flat[0] = 100
print("Original:")
print(matrix)
print("Flattened:")
print(flat)
Output:
Original:
[[1 2]
[3 4]]
Flattened:
[100 2 3 4]
Changing the flattened array does not change the original in this
case because flatten() returns a copy.
22. ravel() — Flattening an Array
np.ravel() or the array method
.ravel() returns a flattened one-dimensional view
whenever possible.
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
flat = matrix.ravel()
print(flat)
Output:
[1 2 3 4 5 6]
23. flatten() vs ravel()
| Feature | flatten() |
ravel() |
|---|---|---|
| Result | 1D array. | 1D array. |
| Copy/View | Returns a copy. | Returns a view when possible. |
| Memory | Requires a separate copy. | Can avoid copying when possible. |
| Typical advantage | Independent flattened data. | Potentially more memory efficient. |
Whether ravel() returns a view or a copy depends
on the array's memory layout and the requested order. Do not
assume that every ravel() result is always a view.
24. reshape() vs flatten()
| Operation | Purpose |
|---|---|
reshape() |
Changes the array's dimensions while preserving the number of elements. |
flatten() |
Converts the array into a 1D copy. |
ravel() |
Converts the array to 1D, using a view when possible. |
25. reshape() Does Not Necessarily Change the Original Shape
Calling reshape() produces an array with the requested
shape. If you want to keep the reshaped result, assign it to a
variable.
numbers = np.arange(1, 7)
reshaped = numbers.reshape(2, 3)
print(numbers.shape)
print(reshaped.shape)
Output:
(6,)
(2, 3)
The original one-dimensional array remains one-dimensional.
26. Converting Between 1D and 2D
A one-dimensional array can be converted into a column-like two-dimensional structure.
numbers = np.array([10, 20, 30, 40])
column = numbers.reshape(4, 1)
print(column)
Output:
[[10]
[20]
[30]
[40]]
It can also be represented as one row:
row = numbers.reshape(1, 4)
print(row)
Output:
[[10 20 30 40]]
27. Data Science Example — Monthly Sales
Suppose sales for 12 months are stored in a one-dimensional array.
sales = np.array([
120, 135, 142, 150,
160, 172, 180, 175,
190, 205, 210, 225
])
We can organize the data into a 3 × 4 structure:
quarter_data = sales.reshape(3, 4)
print(quarter_data)
Output:
[[120 135 142 150]
[160 172 180 175]
[190 205 210 225]]
Reshaping can make data organization more convenient for later analysis, provided the chosen structure matches the meaning of the data.
28. Data Science Example — Image-Like Data
Images are commonly represented as multidimensional numerical arrays. A grayscale image can be represented as a 2D array of pixel values.
image = np.array([
[0, 50, 100],
[150, 200, 255],
[100, 50, 25]
])
print(image.shape)
Output:
(3, 3)
Flattening can convert the pixel grid into a one-dimensional sequence.
pixels = image.flatten()
print(pixels)
This concept is commonly encountered in image processing and Machine Learning workflows.
29. Data Visualization Example — Generating x Values
linspace() is frequently used to generate evenly
spaced points for mathematical functions and visualization.
import numpy as np
x = np.linspace(0, 10, 100)
y = x ** 2
print(x.shape)
print(y.shape)
Both arrays contain 100 values and can be used as coordinates for plotting.
30. Array Creation Cheatsheet
| Function | Purpose | Example |
|---|---|---|
np.array() |
Create from existing data. |
np.array([1, 2, 3])
|
np.arange() |
Generate a sequence using a step. |
np.arange(0, 10, 2)
|
np.linspace() |
Generate evenly spaced values. |
np.linspace(0, 10, 5)
|
np.zeros() |
Create zero-filled array. |
np.zeros((2, 3))
|
np.ones() |
Create one-filled array. |
np.ones((2, 3))
|
np.full() |
Fill an array with a specific value. |
np.full((2, 3), 7)
|
np.empty() |
Allocate an uninitialized array. |
np.empty((2, 3))
|
np.eye() |
Create an identity-style matrix. |
np.eye(3)
|
np.diag() |
Create a diagonal matrix. |
np.diag([1, 2, 3])
|
31. Array Manipulation Cheatsheet
| Operation | Example | Purpose |
|---|---|---|
| Reshape |
arr.reshape(2, 3)
|
Change array dimensions. |
| Flatten |
arr.flatten()
|
Create a 1D copy. |
| Ravel |
arr.ravel()
|
Flatten, using a view when possible. |
| Shape |
arr.shape
|
Inspect dimensions. |
32. NumPy Interview Questions
Q1. What is the difference between np.arange() and np.linspace()?
View Answer
np.arange() generates values based on a
specified step, while np.linspace() generates
a specified number of evenly spaced values between two
endpoints.
Q2. What is the purpose of reshape()?
View Answer
reshape() changes the dimensions of an array
while preserving the total number of elements.
Q3. What happens if the requested reshape contains a different number of elements?
View Answer
NumPy raises a ValueError because the total
number of elements before and after reshaping must match.
Q4. What is the difference between flatten() and ravel()?
View Answer
flatten() returns a copy, whereas
ravel() returns a flattened array and may
return a view when possible.
Q5. What does -1 mean in reshape()?
View Answer
It tells NumPy to automatically calculate that dimension from the total number of elements and the other specified dimensions.
Q6. What does np.zeros((3, 4)) create?
View Answer
It creates a 3 × 4 NumPy array containing zeros.
33. Examination Questions
Multiple Choice Questions
Q1. Which NumPy function generates values using a specified step?
np.linspace()np.arange()np.zeros()np.full()
Answer: B — np.arange()
Q2. What is the output of the following?
np.arange(1, 5)
[1 2 3 4 5][1 2 3 4][0 1 2 3 4][2 3 4 5]
Answer: B — [1 2 3 4]
Q3. Which function generates a specified number of evenly spaced values?
np.arange()np.zeros()np.linspace()np.empty()
Answer: C — np.linspace()
Q4. What is the shape of the following array?
np.zeros((3, 4))
(4, 3)(3, 4)(12,)(3, 3)
Answer: B — (3, 4)
Q5. What is the output shape?
arr = np.arange(1, 13)
arr.reshape(3, 4)
(12,)(4, 3)(3, 4)(2, 6)
Answer: C — (3, 4)
Q6. Which method returns a flattened copy?
reshape()flatten()shape()resize()
Answer: B — flatten()
Short Answer Questions
-
Explain the purpose of
np.arange()with an example. -
Explain
np.linspace()and state one difference between it andnp.arange(). - Write Python statements to create a 3 × 3 array containing zeros.
- Write Python statements to create a 2 × 4 array containing ones.
- What is reshaping? State the basic rule that must be followed when reshaping an array.
-
Differentiate between
flatten()andravel().
34. Practical Challenge
Build a NumPy Array Generator
Create a Python program that demonstrates the major array creation and manipulation techniques covered in this lesson.
-
Create the sequence
1to20usingnp.arange(). -
Generate 6 evenly spaced values between 0 and 1 using
np.linspace(). - Create a 3 × 3 zero-filled array.
- Create a 2 × 4 one-filled array.
- Create a 3 × 3 array filled with the value 7.
- Create an identity matrix of order 4.
- Create an array containing the numbers 1 to 12.
- Reshape it into a 3 × 4 matrix.
-
Flatten the matrix using
flatten(). -
Flatten it using
ravel(). - Display the shape of every important array created.
35. Quick Reference
| Task | Syntax |
|---|---|
| Create array |
np.array([1, 2, 3])
|
| Create sequence |
np.arange(0, 10, 2)
|
| Evenly spaced values |
np.linspace(0, 10, 5)
|
| Zeros |
np.zeros((2, 3))
|
| Ones |
np.ones((2, 3))
|
| Constant values |
np.full((2, 3), 7)
|
| Uninitialized array |
np.empty((2, 3))
|
| Identity matrix |
np.eye(3)
|
| Reshape |
arr.reshape(2, 3)
|
| Automatic dimension |
arr.reshape(3, -1)
|
| Flatten copy |
arr.flatten()
|
| Flatten/view when possible |
arr.ravel()
|
36. Key Takeaways
-
np.array()creates an ndarray from existing data. -
np.arange()generates values using a step. -
The stop value in
np.arange()is normally excluded. -
np.linspace()generates a specified number of evenly spaced values. -
The endpoint is included by default in
np.linspace(). -
np.zeros()creates zero-filled arrays. -
np.ones()creates one-filled arrays. -
np.full()creates arrays filled with a specified value. -
np.empty()allocates an array without initializing its values to a specific number. -
np.eye()creates an identity-style matrix. -
reshape()changes array structure without changing the number of elements. - The total number of elements must remain constant during reshaping.
-
-1allows NumPy to infer one reshape dimension. -
flatten()creates a flattened copy. -
ravel()flattens an array and may return a view when possible.
Use arange() when you know the step,
linspace() when you know the number of points,
and reshape() when you need to reorganize
existing array data without changing its total element
count.