0% found this document useful (0 votes)
16 views15 pages

Exp 12345

The document provides a comprehensive guide on creating and manipulating NumPy arrays, covering topics such as creating basic ndarrays, arrays of zeros and ones, generating random numbers, and creating identity matrices. It also explains array dimensions, shapes, sizes, reshaping, flattening, and transposing arrays, along with expanding and squeezing arrays, sorting, stacking, and concatenating. Additionally, it details indexing and slicing techniques for 1D, 2D, and 3D arrays, including negative slicing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views15 pages

Exp 12345

The document provides a comprehensive guide on creating and manipulating NumPy arrays, covering topics such as creating basic ndarrays, arrays of zeros and ones, generating random numbers, and creating identity matrices. It also explains array dimensions, shapes, sizes, reshaping, flattening, and transposing arrays, along with expanding and squeezing arrays, sorting, stacking, and concatenating. Additionally, it details indexing and slicing techniques for 1D, 2D, and 3D arrays, including negative slicing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

1.

Creating a NumPy Array


a. Basic ndarray
b. Array of zeros
c. Array of ones
d. Random numbers in ndarray
e. An array of your choice
f. Imatrix in NumPy
g. Evenly spaced ndarray

a. Basic ndarray
A NumPy array (ndarray) is a multi-dimensional container for homogeneous data. We can create
it using np.array().

basic_array = np.array([1, 2, 3, 4, 5])


print("Basic ndarray:\n", basic_array)

Output:
Basic ndarray:
[1 2 3 4 5]

b. Array of Zeros
We can create an array filled with zeros using np.zeros().

zeros_array = np.zeros((3, 3))


print("\nArray of zeros:\n", zeros_array)

Explanation:

 np.zeros((3, 3)) creates a 3x3 array filled with 0.0.


 Default data type is float64.

Array of zeros:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

c. Array of Ones
We can create an array filled with ones using np.ones().

ones_array = np.ones((2, 4))


print("\nArray of ones:\n", ones_array)

Explanation:

 np.ones((2, 4)) creates a 2x4 array filled with 1.


 Default data type is float64.
Output:
Array of ones:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]

d. Random Numbers in ndarray


We can generate an array with random values using np.random.rand().

random_array = np.random.rand(3, 3)
print("\nRandom numbers array:\n", random_array)

Explanation:

 np.random.rand(3, 3) creates a 3x3 array with random values between 0 and 1.

Output (Values Will Vary):


Random numbers array:
[[0.65783928 0.98253749 0.32107821]
[0.12498427 0.76350917 0.54721355]
[0.98675105 0.13456832 0.89932275]]

(Note: The numbers will be different each time you run the program.)

e. An Array of Your Choice


You can create an array with specific values using np.array().

custom_array = np.array([[10, 20, 30], [40, 50, 60]])


print("\nAn array of your choice:\n", custom_array)

Explanation:

 np.array([[10, 20, 30], [40, 50, 60]]) creates a 2D NumPy array.

Output:
An array of your choice:
[[10 20 30]
[40 50 60]]

f. Identity Matrix in NumPy (Imatrix)


An identity matrix (also called a unit matrix) is a square matrix with 1s on the diagonal and 0s
elsewhere. We can create it using np.eye().

identity_matrix = np.eye(4)
print("\nIdentity Matrix:\n", identity_matrix)
Explanation:

 np.eye(4) creates a 4x4 identity matrix.

Output:
Identity Matrix:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

g. Evenly spaced ndarray


In NumPy, you can create an evenly spaced ndarray using the numpy.linspace() and
numpy.arange() functions.

1. Using numpy.linspace()

This function returns an array of evenly spaced values over a specified range.

Syntax:
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

 start: The starting value of the sequence.


 stop: The end value of the sequence.
 num: The number of samples to generate (default is 50).
 endpoint: If True, stop is included in the sequence; otherwise, it is excluded.
 retstep: If True, the function also returns the step size.
 dtype: The type of the output array.

Example:
import numpy as np

arr = np.linspace(1, 10, 5)


print(arr)

Output:
css
CopyEdit
[ 1. 3.25 5.5 7.75 10. ]

Here, NumPy created an array with 5 evenly spaced values between 1 and 10.

2. Using numpy.arange()

This function returns evenly spaced values within a given interval.

Syntax:
numpy.arange(start, stop, step, dtype=None)

 start: The starting value of the sequence.


 stop: The end value (excluded).
 step: The spacing between values.

1. The Shape and Reshaping of NumPy Array


a. Dimensions of NumPy array
b. Shape of NumPy array
c. Size of NumPy array
d. Reshaping a NumPy array
e. Flattening a NumPy array
 dtype: The type of the output array.

Example:
arr = np.arange(1, 10, 2)
print(arr)

Output:
[1 3 5 7 9]

Here, NumPy created an array with a step size of 2 from 1 to 9 (excluding 10).

2 . The Shape and Reshaping of NumPy Array

a. Dimensions of NumPy array

b. Shape of NumPy array

c. Size of NumPy array

d. Reshaping a NumPy array

e. Flattening a NumPy array

f. Transpose of a NumPy array

a. Dimensions of a NumPy Array (ndim)


The number of dimensions of a NumPy array is called its rank. You can determine it using the
.ndim attribute.

Example:
import numpy as np

# Creating arrays with different dimensions


arr_1d = np.array([1, 2, 3])
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(arr_1d.ndim) # Output: 1
print(arr_2d.ndim) # Output: 2
print(arr_3d.ndim) # Output: 3

b. Shape of a NumPy Array (shape)


The shape of a NumPy array represents its dimensions as a tuple of integers (rows, columns,
depth, ...).

Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # Output: (2, 3)

This means the array has 2 rows and 3 columns.

c. Size of a NumPy Array (size)


The size of a NumPy array is the total number of elements in the array.

Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.size) # Output: 6

This means the array has 6 elements.

d. Reshaping a NumPy Array (reshape())


Reshaping means changing the shape (dimensions) of an array without altering its data.

Example:
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, 3)
print(reshaped_arr)

Output:
[[1 2 3]
[4 5 6]]

Here, a 1D array of 6 elements is reshaped into a 2D array of shape (2,3).

⚠ Note: The total number of elements must remain the same after reshaping.

e. Flattening a NumPy Array (flatten())


Flattening converts a multi-dimensional array into a 1D array.

Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
flat_arr = arr.flatten()
print(flat_arr)

Output:
[1 2 3 4 5 6]

The 2D array is now converted into a 1D array.

f. Transpose of a NumPy Array (transpose() or .T)


The transpose of a matrix swaps its rows with its columns.

Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
transposed_arr = arr.T # or np.transpose(arr)
print(transposed_arr)

Output:
[[1 4]
[2 5]
[3 6]]

The 2x3 matrix is now converted into a 3x2 matrix.

3. Expanding and Squeezing a NumPy Array

a. Expanding a NumPy array

b. Squeezing a NumPy array

c. Sorting in NumPy Arrays

NumPy provides tools to add or remove dimensions from an array using np.expand_dims()
and np.squeeze().

a. Expanding a NumPy Array (np.expand_dims())

This function adds an extra dimension to an array.

Example:
import numpy as np

arr = np.array([1, 2, 3])


expanded_arr = np.expand_dims(arr, axis=0) # Adds a new axis at index 0
print(expanded_arr)
print(expanded_arr.shape)

Output:
[[1 2 3]]
(1, 3)

Here, a 1D array (3,) is expanded to 2D (1,3).

b. Squeezing a NumPy Array (np.squeeze())

This function removes dimensions with size 1.

Example:
arr = np.array([[[1, 2, 3]]]) # Shape (1,1,3)
squeezed_arr = np.squeeze(arr)
print(squeezed_arr)
print(squeezed_arr.shape)

Output:
[1 2 3]
(3,)
Here, extra dimensions (1,1,3) → (3,) are removed.

c. Sorting in NumPy Arrays (np.sort())

NumPy provides sorting using np.sort(), which returns a sorted copy of an array.

Example:
arr = np.array([3, 1, 2, 5, 4])
sorted_arr = np.sort(arr)
print(sorted_arr)

Output:
[1 2 3 4 5]

Sorting also works for 2D arrays:

arr_2d = np.array([[3, 2, 1], [6, 5, 4]])


sorted_arr_2d = np.sort(arr_2d, axis=1) # Sort row-wise
print(sorted_arr_2d)

Output:
[[1 2 3]
[4 5 6]]

5. Stacking and Concatenating NumPy Arrays


a. Stacking ndarrays (np.stack(), np.hstack(), np.vstack())

Stacking joins arrays along a new axis.

Example:
python
CopyEdit
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

stacked = np.stack((arr1, arr2), axis=0) # Stack along rows


print(stacked)

Output:
lua
CopyEdit
[[1 2 3]
[4 5 6]]

Other stacking methods:

 np.hstack((arr1, arr2)) → Horizontal stacking


 np.vstack((arr1, arr2)) → Vertical stacking

b. Concatenating ndarrays (np.concatenate())


Concatenation merges arrays along an existing axis.

Example:
python
CopyEdit
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6]])

concat_arr = np.concatenate((arr1, arr2), axis=0)


print(concat_arr)

Output:
lua
CopyEdit
[[1 2]
[3 4]
[5 6]]

c. Broadcasting in NumPy Arrays

Broadcasting allows operations on arrays of different shapes.

Example:
python
CopyEdit
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([1, 2, 3]) # 1D array

result = arr1 + arr2 # Broadcasts arr2 across arr1


print(result)

Output:
lua
CopyEdit
[[ 2 4 6]
[ 5 7 9]]

Here, arr2 (1,3) is broadcasted to match arr1 (2,3).

4. Indexing and Slicing of NumPy Array

a. Slicing 1-D NumPy arrays

b. Slicing 2-D NumPy arrays

c. Slicing 3-D NumPy arrays

d. Negative slicing of NumPy arrays

NumPy allows efficient indexing and slicing of arrays, making it easy to access and modify
elements. Let's explore slicing for 1D, 2D, and 3D arrays along with negative slicing.

a. Slicing 1-D NumPy Arrays


Slicing extracts a subset of elements from an array using the syntax:

array[start:stop:step]

 start: Index to start slicing (inclusive, default = 0).


 stop: Index to stop slicing (exclusive).
 step: Step size (default = 1).

Example:
import numpy as np

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

print(arr[2:7]) # Elements from index 2 to 6


print(arr[:5]) # First 5 elements
print(arr[3:]) # Elements from index 3 to end
print(arr[::2]) # Every 2nd element

Output:
[2 3 4 5 6]
[0 1 2 3 4]
[3 4 5 6 7 8 9]
[0 2 4 6 8]

b. Slicing 2-D NumPy Arrays


For 2D arrays, the slicing format is:

array[row_start:row_end, column_start:column_end]

Example:
arr_2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

print(arr_2d[1:, :2]) # Last two rows, first two columns


print(arr_2d[:2, 1:]) # First two rows, last two columns
print(arr_2d[::2, ::2]) # Every alternate row and column

Output:
[[4 5]
[7 8]]

[[2 3]
[5 6]]

[[1 3]
[7 9]]

c. Slicing 3-D NumPy Arrays


For 3D arrays, slicing follows the format:

array[depth_start:depth_end, row_start:row_end, col_start:col_end]

Example:
arr_3d = np.array([[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
[[13, 14, 15], [16, 17, 18]]])

print(arr_3d[1:, :, :]) # All elements from depth index 1 onwards


print(arr_3d[:, 1, :]) # All second rows from each depth slice
print(arr_3d[:, :, ::2]) # Every alternate column from all depth levels

Output:
[[[ 7 8 9]
[10 11 12]]

[[13 14 15]
[16 17 18]]]

[[ 4 5 6]
[10 11 12]
[16 17 18]]

[[[ 1 3]
[ 4 6]]

[[ 7 9]
[10 12]]

[[13 15]
[16 18]]]

d. Negative Slicing of NumPy Arrays


Negative slicing in NumPy allows extracting elements from the end of an array. Instead of
counting from the start (0, 1, 2, ...), negative indices start from -1 (last element), -2
(second last), and so on.

Syntax:
array[start:stop:step]

 start: The starting index (negative values count from the end).
 stop: The stopping index (exclusive, negative values count from the end).
 step: The step size (negative step reverses the order).

1. Negative Slicing in 1D Arrays


Example:
import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

print(arr[-5:]) # Last 5 elements


print(arr[:-3]) # All elements except the last 3
print(arr[::-1]) # Reverse the array
print(arr[-7:-2]) # Elements from index -7 to -3
print(arr[-8::-1]) # First 3 elements in reverse

Output:
[60 70 80 90 100]
[10 20 30 40 50 60 70]
[100 90 80 70 60 50 40 30 20 10]
[30 40 50 60 70]
[30 20 10]

2. Negative Slicing in 2D Arrays


For 2D arrays, negative slicing works on rows and columns.

Example:
arr_2d = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])

print(arr_2d[-2:, -3:]) # Last 2 rows, last 3 columns


print(arr_2d[:-1, :-2]) # All rows except last, all columns except last 2
print(arr_2d[::-1, ::-1]) # Reverse rows and columns

Output:
[[10 11 12]
[14 15 16]]

[[ 1 2]
[ 5 6]
[ 9 10]]

[[16 15 14 13]
[12 11 10 9]
[ 8 7 6 5]
[ 4 3 2 1]]

3. Negative Slicing in 3D Arrays


For 3D arrays, slicing works across depth, rows, and columns.

Example:
arr_3d = np.array([[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
[[13, 14, 15], [16, 17, 18]]])

print(arr_3d[-2:, :, -2:]) # Last 2 depth slices, all rows, last 2 columns


print(arr_3d[::-1, ::-1, ::-1]) # Reverse depth, rows, and columns

Output:
[[[ 8 9]
[11 12]]

[[14 15]
[17 18]]]

[[[18 17 16]
[15 14 13]]

[[12 11 10]
[ 9 8 7]]

[[ 6 5 4]
[ 3 2 1]]]

5. Stacking and Concatenating Numpy Arrays

a. Stacking ndarrays

b. Concatenating ndarrays

c. Broadcasting in Numpy Arrays

NumPy provides powerful functions to combine multiple arrays in different ways. Two main
techniques are:

1. Stacking (joins along new axes)


2. Concatenation (joins along existing axes)
3. Broadcasting (automatic expansion of arrays for operations)

a. Stacking ndarrays
Stacking adds a new axis to combine arrays either vertically, horizontally, or along depth.

1. np.vstack() → Vertical Stacking (Row-wise)

Stacks arrays along axis 0 (adds new rows).

import numpy as np

arr1 = np.array([1, 2, 3])


arr2 = np.array([4, 5, 6])

result = np.vstack((arr1, arr2))


print(result)

Output:
[[1 2 3]
[4 5 6]]
2. np.hstack() → Horizontal Stacking (Column-wise)

Stacks arrays along axis 1 (adds new columns).

arr1 = np.array([[1, 2, 3]])


arr2 = np.array([[4, 5, 6]])

result = np.hstack((arr1, arr2))


print(result)

Output:
[[1 2 3 4 5 6]]

3. np.dstack() → Depth Stacking

Stacks arrays along the third axis (depth).

arr1 = np.array([[1, 2], [3, 4]])


arr2 = np.array([[5, 6], [7, 8]])

result = np.dstack((arr1, arr2))


print(result)

Output:
[[[1 5]
[2 6]]

[[3 7]
[4 8]]]

4. np.stack() → Custom Axis Stacking

Allows stacking along any axis using the axis parameter.

arr1 = np.array([1, 2, 3])


arr2 = np.array([4, 5, 6])

result = np.stack((arr1, arr2), axis=1) # Stacks along axis 1


print(result)

Output:
[[1 4]
[2 5]
[3 6]]

b. Concatenating ndarrays
Concatenation joins arrays along an existing axis without adding a new one.

1. np.concatenate()

Concatenates arrays along a specified axis (default axis=0).


arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6]])

result = np.concatenate((arr1, arr2), axis=0) # Concatenating along rows


print(result)

Output:
[[1 2]
[3 4]
[5 6]]

2. Concatenating Along Columns (axis=1)


arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])

result = np.concatenate((arr1, arr2), axis=1) # Concatenating along columns


print(result)

Output:
[[1 2 5 6]
[3 4 7 8]]

3. np.column_stack() → Column-wise Concatenation


arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

result = np.column_stack((arr1, arr2))


print(result)

Output:
[[1 4]
[2 5]
[3 6]]

4. np.row_stack() → Row-wise Concatenation


arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

result = np.row_stack((arr1, arr2))


print(result)

Output:
[[1 2 3]
[4 5 6]]

c. Broadcasting in NumPy Arrays


Broadcasting allows NumPy to perform arithmetic operations on arrays of different shapes by
automatically expanding smaller arrays.
1. Adding a Scalar to an Array
arr = np.array([1, 2, 3])
result = arr + 10 # NumPy automatically expands 10 to match array shape
print(result)

Output:
[11 12 13]

2. Broadcasting a 1D Array to a 2D Array


arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([10, 20, 30]) # Shape (3,) expands to match (2,3)

result = arr1 + arr2


print(result)

Output:
[[11 22 33]
[14 25 36]]

3. Broadcasting in Multiplication
arr1 = np.array([[1], [2], [3]]) # Shape (3,1)
arr2 = np.array([10, 20, 30]) # Shape (3,)

result = arr1 * arr2


print(result)

Output:
[[10 20 30]
[20 40 60]
[30 60 90]]

You might also like