0% found this document useful (0 votes)
13 views18 pages

NumPy Array Operations and Manipulations

The document contains various Python code snippets using the NumPy library to create and manipulate arrays. It covers creating 1D and 2D arrays, extracting elements, reshaping, copying, stacking, splitting, and sorting arrays. Each section includes code examples and expected outputs for clarity.

Uploaded by

singhsamridhi813
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views18 pages

NumPy Array Operations and Manipulations

The document contains various Python code snippets using the NumPy library to create and manipulate arrays. It covers creating 1D and 2D arrays, extracting elements, reshaping, copying, stacking, splitting, and sorting arrays. Each section includes code examples and expected outputs for clarity.

Uploaded by

singhsamridhi813
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Samridhi

Zarnain Singh
MAURYAQureshi
SUMAN

[Link] a 1D NumPy array of the first 10 even numbers starting from 2 and a 2D 3x3 array with
numbers from 1 to 9. Display both arrays.

# Importing the NumPy library

import numpy as np

# -------------------------------------------

# 1. Create a 1D NumPy array of the first 10 even numbers starting from 2

# Even numbers starting from 2 are: 2, 4, 6, 8, ..., 20

# We use [Link](start, stop, step)

# Here, start=2, stop=21 (since it excludes 21), and step=2

even_numbers = [Link](2, 21, 2)

# -------------------------------------------

# 2. Create a 2D 3x3 NumPy array with numbers from 1 to 9

# First, we use [Link](1, 10) to create 1D array [1, 2, ..., 9]

# Then we use .reshape(3, 3) to convert it into a 3x3 2D array

matrix_3x3 = [Link](1, 10).reshape(3, 3)

# -------------------------------------------

# Displaying both arrays with labels

print("1D NumPy Array (First 10 Even Numbers starting from 2):")

print(even_numbers)

print("\n2D NumPy Array (3x3 Matrix with Numbers from 1 to 9):")

print(matrix_3x3)

2302020101417 1
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

output:

2302020101417 2
Samridhi
Zarnain
MAURYA Singh
Qureshi
SUMAN

[Link] a 1D NumPy array arr = [Link]([10, 20, 30, 40, 50, 60, 70, 80]), extract and display:

● The first 4 elements.

● Every second element.

● The last 3 elements in reverse order.

# Import the NumPy library

import numpy as np

# Creating the 1D NumPy array

arr = [Link]([10, 20, 30, 40, 50, 60, 70, 80])

# 1. Extract the first 4 elements using slicing

first_four = arr[:4] # Index 0 to 3

# 2. Extract every second element using step in slicing

every_second = arr[::2] # Start to end, step by 2

#3. Extract the last 3 elements in reverse order

last_three_reversed = arr[-1:-4:-1] # Start from end and move backwards

2 the outputs
# Display
MAURYAArray:")
print("Original Zarnain QSUMANureshi
output:
print(arr)

print("\nFirst 4 Elements:")

print(first_four)

print("\nEvery Second Element:")

print(every_second)

print("\nLast 3 Elements in Reverse Order:")

print(last_three_reversed)

3
2302020101417
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

output:

3. Create a 2D NumPy array original = [Link]([[1, 2, 3], [4, 5, 6]]). Perform the following:

2302020101417 4
Zarnain Qureshi
Samridhi
MAURYA Singh
SUMAN

● Create a shallow copy and a deep copy of the array.

● Modify the first element of the first row in both copies to 99.

● Display the original array and both copies to show the difference.

# Importing the NumPy library

import numpy as np

# Create the original 2D array

original = [Link]([[1, 2, 3], [4, 5, 6]])

# Create a shallow copy (view)

shallow_copy = [Link]()

# Create a deep copy

deep_copy = [Link]()

# Modify the first element of the first row in both copies

shallow_copy[0, 0] = 99

deep_copy[0, 0] = 99

# Display all arrays to see the difference

print("Original Array (After modification in shallow and deep copies):")

print(original)

print("\nShallow Copy (Modified):")

print(shallow_copy)

print("\nDeep Copy (Modified):")

print(deep_copy)

output:

2302020101417 5
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

2302020101417 6
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

4. Create a 1D NumPy array with 12 elements (from 1 to 12). Reshape it into:

● A 3x4 array.

● A 2x6 array.

● A 4x3 array. Display all reshaped arrays.

import numpy as np

# Create a 1D NumPy array with 12 elements

arr = [Link](1, 13)

# Reshape the array into different shapes

arr_3x4 = [Link](3, 4)

arr_2x6 = [Link](2, 6)

arr_4x3 = [Link](4, 3)

# Display the original and reshaped arrays

print("Original 1D Array:")

print(arr)

print("\nReshaped Array (3x4):")

print(arr_3x4)

print("\nReshaped Array (2x6):")

print(arr_2x6)

print("\nReshaped Array (4x3):")

print(arr_4x3)

2302020101417 7
Samridhi
Zarnain
MAURYA Singh
Qureshi
SUMAN

output:

2302020101417 8
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

5. Create a 3x3 NumPy array with random integers between 1 and 20. Write a program to:

● Iterate over the array using nditer to print each element.

● Calculate the sum of elements in each row using a nested loop. ● Identify and
display the row with the highest sum.

import numpy as np

# Create a 3x3 array with random integers between 1 and 20

[Link](0) # for reproducibility

arr = [Link](1, 21, size=(3, 3))

# Iterate over array using nditer

print("Array Elements using nditer:")

for element in [Link](arr):

print(int(element), end=' ')

print()

# Calculate the sum of elements in each row using nested loop

row_sums = []

for i in range([Link][0]):

row_sum = 0

for j in range([Link][1]):

row_sum += arr[i][j]

row_sums.append(row_sum)

# Display row sums

print("\nSum of elements in each row:")

for i, total in enumerate(row_sums):

print(f"Row {i}: Sum = {total}")

2302020101417 9
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

# Identify row with highest sum

max_sum = max(row_sums)

max_index = row_sums.index(max_sum)

print(f"\nRow with the highest sum is Row {max_index} with a sum of {max_sum}")

output:

2302020101417 10
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

6. Create two 1D NumPy arrays: arr1 = [Link]([1, 2, 3]) and arr2 = [Link]([4, 5, 6]).

Perform the following:

● Concatenate them into a single array.

● Stack them vertically to form a 2x3 array.

● Stack them horizontally to form a 1x6 array. Display all results and explain the
difference between concatenation and stacking in 2 sentences.

import numpy as np

# Create two 1D arrays

arr1 = [Link]([1, 2, 3])

arr2 = [Link]([4, 5, 6])

# Concatenate the arrays

concatenated = [Link]((arr1, arr2))

# Stack vertically (2 rows, 3 columns)

vertical_stack = [Link]((arr1, arr2))

# Stack horizontally (1 row, 6 columns)

horizontal_stack = [Link]((arr1, arr2))

# Display results

print("Concatenated Array:")

print(concatenated)

print("\nVertically Stacked Array (2x3):")

print(vertical_stack)

2302020101417 11
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

print("\nHorizontally Stacked Array (1x6):")

print(horizontal_stack)

output:

2302020101417 12
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

7. Create a 1D NumPy array with 10 elements (1 to 10). Split it into:

● 5 equal parts.

● 3 parts at indices 3 and 7. Display the resulting sub-arrays.

import numpy as np

# Create a 1D array with 10 elements from 1 to 10

arr = [Link](1, 11)

# Split into 5 equal parts

split_equal = np.array_split(arr, 5)

# Split at indices 3 and 7 (i.e., arr[0:3], arr[3:7], arr[7:10])

split_indices = [Link](arr, [3, 7])

# Display the results

print("Original Array:")

print(arr)

print("\nSplit into 5 Equal Parts:")

for i, part in enumerate(split_equal):

print(f"Part {i+1}: {part}")

print("\nSplit into 3 Parts at Indices 3 and 7:")

for i, part in enumerate(split_indices):

print(f"Part {i+1}: {part}")

2302020101417 13
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

Output:

2302020101417 14
Zarnain Qureshi
Samridhi
MAURYA Singh
SUMAN

8. Create a 1D NumPy array with 15 random integers between 1 and 50. Write a program to:

● Find the indices of all elements greater than 30.

● Use [Link] to replace all elements less than 10 with 0.

● Display the original and modified arrays, and the indices found.

import numpy as np

# Create a 1D array with 15 random integers between 1 and 50

[Link](0) # For reproducibility

arr = [Link](1, 51, size=15)

# Find indices of elements greater than 30

indices_gt_30 = [Link](arr > 30)[0]

# Replace elements less than 10 with 0 using [Link]

modified_arr = [Link](arr < 10, 0, arr)

# Display results

print("Original Array:")

print(arr)

print("\nIndices of elements greater than 30:")

print(indices_gt_30)

print("\nModified Array (elements < 10 replaced with 0):")

print(modified_arr)

2302020101417 15
Zarnain Qureshi
Samridhi
MAURYA Singh
SUMAN

Output:

2302020101417 16
Samridhi
Zarnain
MAURYA Singh
Qureshi
SUMAN

9. Create a 2D 4x3 NumPy array with random integers between 1 and 100. Write a program to:

● Sort each row in ascending order.

● Sort the entire array based on the first column in descending order.

import numpy as np

# Create a 2D 4x3 array with random integers between 1 and 100

[Link](0) # For reproducibility

arr = [Link](1, 101, size=(4, 3))

# Sort each row in ascending order

sorted_rows = [Link](arr, axis=1)

# Sort the entire array based on the first column in descending order

sorted_by_first_col = arr[arr[:, 0].argsort()[::-1]]

# Display results

print("Original Array:")

print(arr)

print("\nSorted Rows (each row in ascending order):")

print(sorted_rows)

print("\nArray Sorted by the First Column in Descending Order:")

print(sorted_by_first_col)

2302020101417 17
Samridhi Singh
Zarnain Qureshi
MAURYA SUMAN

Output:

2302020101417 18

You might also like