Skip to main content
Pandas & NumPy
CHAPTER 03 Beginner

NumPy Arrays Basics

Updated: May 18, 2026
5 min read

# CHAPTER 3

NumPy Arrays Basics

1. Chapter Introduction

The ndarray (N-dimensional array) is NumPy's core. It stores elements of the same type in a contiguous memory block — enabling C-speed computation from Python. Understanding arrays is the foundation of all numerical computing in Python.

2. Creating Arrays

python
1234567891011121314151617
import numpy as np

# From Python list
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)           # [1 2 3 4 5]
print(type(arr1))     # <class 'numpy.ndarray'>

# 2D array (matrix)
arr2d = np.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
print(arr2d)

# 3D array
arr3d = np.array([[[1, 2], [3, 4]],
                  [[5, 6], [7, 8]]])
print(arr3d.shape)    # (2, 2, 2)

3. Array Creation Functions

python
123456789101112131415161718
# Zeros and ones
zeros = np.zeros((3, 4))          # 3x4 matrix of 0.0
ones  = np.ones((2, 3), dtype=int) # 2x3 matrix of 1
full  = np.full((3, 3), 7)        # 3x3 matrix of 7

# Ranges
arange = np.arange(0, 20, 2)     # [0 2 4 6 8 10 12 14 16 18]
linspace = np.linspace(0, 1, 5)  # [0.   0.25 0.5  0.75 1.  ]

# Identity matrix
eye = np.eye(4)                   # 4x4 identity

# Empty (uninitialized — fast)
empty = np.empty((2, 2))

print("zeros:\n", zeros)
print("arange:", arange)
print("linspace:", linspace)

4. Array Attributes

python
123456789
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

print(f"ndim:    {arr.ndim}")    # 2 (dimensions)
print(f"shape:   {arr.shape}")   # (2, 3) — 2 rows, 3 cols
print(f"size:    {arr.size}")    # 6 (total elements)
print(f"dtype:   {arr.dtype}")   # int64
print(f"itemsize:{arr.itemsize}")# 8 bytes per element
print(f"nbytes:  {arr.nbytes}")  # 48 bytes total

5. Data Types

python
123456789101112131415161718
# NumPy dtypes
int_arr   = np.array([1, 2, 3], dtype=np.int32)
float_arr = np.array([1.5, 2.5, 3.5], dtype=np.float64)
bool_arr  = np.array([True, False, True], dtype=np.bool_)
str_arr   = np.array([&#039;a', 'b', 'c'], dtype=np.str_)
complex_arr = np.array([1+2j, 3+4j])

print(int_arr.dtype)     # int32
print(float_arr.dtype)   # float64

# Type conversion (astype)
int_from_float = float_arr.astype(np.int32)
print(int_from_float)    # [1 2 3]

# Common dtypes:
# np.int8, np.int16, np.int32, np.int64
# np.float32, np.float64
# np.bool_, np.str_, np.complex128

6. Reshape and Resize

python
1234567891011121314151617
arr = np.arange(12)
print(arr)             # [0  1  2  3  4  5  6  7  8  9 10 11]

# Reshape (must keep same total elements)
reshaped = arr.reshape(3, 4)   # 3 rows, 4 cols
print(reshaped)

reshaped_3d = arr.reshape(2, 2, 3)
print(reshaped_3d.shape)       # (2, 2, 3)

# -1 means "figure out this dimension"
auto = arr.reshape(4, -1)      # (4, 3) — 4 rows, auto cols
print(auto.shape)

# Flatten back to 1D
flat = reshaped.flatten()
print(flat)                    # [0 1 2 ... 11]

7. Mini Project: Matrix Generator

python
123456789101112131415161718192021222324
import numpy as np

def generate_matrix(rows, cols, matrix_type=&#039;zeros'):
    """Generate various types of matrices for analysis."""
    if matrix_type == &#039;zeros':
        return np.zeros((rows, cols), dtype=int)
    elif matrix_type == &#039;ones':
        return np.ones((rows, cols), dtype=int)
    elif matrix_type == &#039;identity':
        return np.eye(min(rows, cols))
    elif matrix_type == &#039;random':
        return np.random.randint(1, 100, (rows, cols))
    elif matrix_type == &#039;diagonal':
        values = np.arange(1, min(rows, cols) + 1)
        return np.diag(values)
    elif matrix_type == &#039;range':
        return np.arange(rows * cols).reshape(rows, cols)

# Generate and display
for mtype in [&#039;zeros', 'ones', 'random', 'range', 'identity']:
    mat = generate_matrix(3, 4, mtype)
    print(f"\n--- {mtype.upper()} MATRIX ({mat.shape}) ---")
    print(mat)
    print(f"Sum: {mat.sum()}, Mean: {mat.mean():.2f}")

8. Common Mistakes

  • Mutable list vs immutable shape: Once created, a NumPy array's dtype is fixed. Adding a float to an int array converts automatically but may lose precision.
  • reshape vs resize: reshape returns a new view with different shape. resize modifies in-place and can change total element count.

9. MCQs

Question 1

np.zeros((3,4)) creates?

Question 2

arr.ndim returns?

Question 3

arr.shape for a 2x3 array?

Question 4

np.arange(0, 10, 2) produces?

Question 5

arr.astype(np.float32) does?

Question 6

arr.reshape(4, -1) where arr has 12 elements?

Question 7

arr.flatten() returns?

Question 8

np.linspace(0, 1, 5) produces?

Question 9

arr.nbytes returns?

Question 10

np.eye(3) creates?

10. Interview Questions

  • Q: What is the difference between np.zeros, np.ones, and np.empty?
  • Q: Why must all elements in a NumPy array have the same dtype?

11. Summary

NumPy's ndarray provides multi-dimensional array storage with fixed dtype, enabling C-speed computation. Key attributes: ndim, shape, size, dtype, nbytes. Array creation functions (zeros, ones, arange, linspace, eye) cover every common use case.

12. Next Chapter Recommendation

In Chapter 4: NumPy Array Operations, we perform arithmetic, reshaping, concatenation, and statistical operations on arrays.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·