02. NumPy Array Basics: Create and Handle Arrays in Python
1. Creating Arrays with np.array()
You can create arrays manually using Python lists.
1
2
3
4
5
6
7
8
9
10
import numpy as np
A = np.array([
[1, -1, 2],
[3, 2, 2],
[4, 1, 2],
[7, 5, 6]
])
print(A)
Output:
1
2
3
4
[[ 1 -1 2]
[ 3 2 2]
[ 4 1 2]
[ 7 5 6]]
Here, A is a 4×3 array.
2. Another Example of np.array()
1
2
3
4
5
6
7
B = np.array([
[0, 1],
[-1, 3],
[5, 2]
])
print(B)
Output:
1
2
3
[[ 0 1]
[-1 3]
[ 5 2]]
B is a 3×2 array.
3. Creating Random Arrays with np.random.rand()
The np.random.rand() function generates random numbers between 0 and 1.
1
2
C = np.random.rand(3, 5)
print(C)
Example Output:
1
2
3
[[0.7720613 0.34936775 0.55718465 0.83078859 0.84575107]
[0.18550725 0.06023345 0.36876688 0.14548477 0.80038621]
[0.69913545 0.09887855 0.38529517 0.65256723 0.48723025]]
This creates a 3×5 array filled with random floating-point numbers.
4. Creating Zero Arrays with np.zeros()
To create an array filled with zeros:
1
2
D = np.zeros((2, 4))
print(D)
Output:
1
2
[[0. 0. 0. 0.]
[0. 0. 0. 0.]]
D is a 2×4 array filled with zeros.
5. Accessing Elements in an Array
You can access individual elements using indexing.
1
2
value = A[0][2]
print(value)
Output:
1
2
This gets the element from the first row (index 0) and third column (index 2) of array A.
Summary
np.array()→ create arrays from listsnp.random.rand()→ generate random arraysnp.zeros()→ create arrays filled with zeros- Indexing → access specific elements
NumPy makes numerical computation in Python fast and easy!
This post is licensed under CC BY 4.0 by the author.