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

تلخيص numPy

NumPy, short for Numerical Python, is a powerful library for numerical computing in Python, providing support for large multi-dimensional arrays and matrices, along with mathematical functions for efficient operations. It allows for array creation, element-wise operations, indexing, slicing, and includes features like broadcasting and reshaping. NumPy serves as the foundational package for high-performance computing and data analysis, being essential for libraries such as SciPy, pandas, and scikit-learn.

Uploaded by

Yosra Yaseen
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)
4 views15 pages

تلخيص numPy

NumPy, short for Numerical Python, is a powerful library for numerical computing in Python, providing support for large multi-dimensional arrays and matrices, along with mathematical functions for efficient operations. It allows for array creation, element-wise operations, indexing, slicing, and includes features like broadcasting and reshaping. NumPy serves as the foundational package for high-performance computing and data analysis, being essential for libraries such as SciPy, pandas, and scikit-learn.

Uploaded by

Yosra Yaseen
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

NumPy

• Stands for Numerical Python


• NumPy is a powerful library in Python that is widely used for numerical computing. It provides support
for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to
operate on these arrays.
• Is the fundamental package required for high performance computing and data analysis
• NumPy is so important for numerical computations in Python is because it is designed for efficiency on
large arrays of data.
• It provides
• ndarray for creating multiple dimensional arrays
• Internally stores data in a contiguous block of memory, independent of other built-in Python
objects, use much less memory than built-in Python sequences.
• Standard math functions for fast operations on entire arrays of data without having to write loops
• NumPy Arrays are important because they enable you to express batch operations on data
without writing any for loops. We call this vectorization.
1. Array Creation:
a. Creating arrays: You can create a NumPy array using the numpy.array() function.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr) # output: [1 2 3 4]
b. Creating arrays with zeros, ones, or a range:
np.zeros((2, 3)) # 2x3 array filled with zeros
np.ones((3, 2)) # 3x2 array filled with ones
np.arange(10) # Array with values from 0 to 9
c. Random arrays:
np.random.random((2, 3)) # Random 2x3 array with values between 0 and 1
2. Array Operations:
NumPy arrays support element-wise operations like addition, subtraction, multiplication, and
division.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

sum_arr = arr1 + arr2 # Element-wise addition


product_arr = arr1 * arr2 # Element-wise multiplication
3. Array Indexing and Slicing:
You can access and modify elements of an array using indexing and slicing.
arr = np.array([10, 20, 30, 40, 50])
print(arr[2]) # Access element at index 2
print(arr[1:4]) # Slice from index 1 to 3
4. Multi-dimensional arrays:
NumPy supports multi-dimensional arrays (e.g., matrices).
python
Copy code
mat = np.array([[1, 2], [3, 4], [5, 6]])
print(mat)
5. Mathematical Functions:
NumPy provides a range of mathematical functions like sum, mean, standard deviation, etc.
arr = np.array([1, 2, 3, 4, 5])
print(np.sum(arr)) # Sum of all elements
print(np.mean(arr)) # Mean of all elements
print(np.std(arr)) # Standard deviation
6. Linear Algebra:
NumPy also has a submodule for linear algebra operations, such as matrix multiplication.
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[5, 6], [7, 8]])
result = np.dot(mat1, mat2) # Matrix multiplication
7. Reshaping Arrays:
NumPy allows you to reshape arrays, which is useful for changing their dimensions.
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, 3) # Reshape into 2x3 matrix
8. Broadcasting:
NumPy can perform operations between arrays of different shapes through a feature called
broadcasting.
arr1 = np.array([1, 2, 3])
arr2 = np.array([10])
result = arr1 + arr2 # Broadcasting arr2 to the shape of arr1
9. Useful Functions:
Some other useful functions in NumPy include:
 np.min(), np.max(): To find the minimum and maximum values of an array.

 np.argmax(), np.argmin(): To find the index of the maximum and minimum values.

 np.transpose(): To transpose matrices.


Example Code:
Here’s a simple example of creating an array, performing operations, and reshaping:
import numpy as np
# Create a 1D array
arr = np.array([1, 2, 3, 4, 5])
print("Original Array:", arr)

# Sum and mean


print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))

# Reshape to a 2D array (matrix)


reshaped_arr = arr.reshape(1, 5)
print("Reshaped Array:", reshaped_arr)

# Perform element-wise multiplication


arr2 = np.array([1, 1, 1, 1, 1])
product = arr * arr2
print("Element-wise product:", product)
NumPy is essential for working with numerical data in Python, and it serves as the foundation for
many other libraries, including SciPy, pandas, and scikit-learn.
OUTPUT

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


print(arr)
print(np.zeros((2, 3))) [[0. 0. 0.] 2x3 ‫انشاء مصفوفة‬
[0. 0. 0.]] ‫كل عناصرها صفر‬
print(np.ones((2, 3))) [[1. 1. 1.] 2 ‫انشاء مصفوفة‬x3
[1. 1. 1.]] ‫كل عناصرها واحد‬
print(np.random.random((2, 3))) [[0.50699473 0.99940988 # Random 2x3
0.06254377] array with values
[0.24955772 0.50108726 [0, 1)
0.30190725]] 0 ‫قيم عشوائية من‬
2x3 ‫ لمصفوفة‬1 ‫ال‬
arr1 = np.array([1, 2, 3]) [5 7 9] ‫جمع مصفوفتين‬
arr2 = np.array([4, 5, 6]) [ 4 10 18] ‫ضرب مصفوفتين‬
print(arr1 + arr2) # [5 7 9]
print(arr1 * arr2) # [4 10 18]
arr = np.array([10, 20, 30, 40]) 20
print(arr[1]) # 20 [20 30] slicing
print(arr[1:3]) # [20 30]
mat = np.array([[1, 2], [3, 4], [5, 6]]) 4 ‫ العامود‬mat[1, 1]
print(mat[1, 1]) # 4 [1 3 5] ‫االول في الصف‬
print(mat[:, 0]) # [1 3 5] ‫االول‬
‫ جميع‬mat[:, 0]
‫الصفوف في‬
)‫العامود صفر(االول‬

arr = np.array([1, 2, 3]) [6 7 8] (Broadcasting


print(arr + 5) # [6 7 8] scalar 5)
‫ لكل‬5 ‫جمع العدد‬
‫عنصر من عناصر‬
‫المصفوفة‬
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [3 6 9] ‫العناصرالموجوده‬
print(arr[:, 2]) ‫ فقط‬2 ‫في الموقع‬
arr = np.arange(10) ‫العشرة ال تشمل‬ [0 1 2 3 4 5 6 7 8 9] arrange
‫العناصر‬ ‫القيم المحصورة‬
print(arr) 9 ‫بين الصفر وال‬
arr = np.arange(10) # 0 1 2 3 4 5 6 7 8 9 [ 0 1 2 3 4 12 12 12 8 9] ‫استبدال كل القيم‬
arr[5:8] = 12 7-5 ‫من‬ 7 ‫ الى‬5 ‫من الموقع‬
print(arr) 12 ‫بالقيمة‬
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) arr2d[1, :2]
print(arr2d[1, :2]) ‫ رقم المصفوفة‬1
‫ من البداية الى‬2:
1 2 3 4 5 6 7 8 9 ‫العصنر الثاني ( اي‬
)‫عنصرين من البداية‬

0 1 2

arr = np.array([[1, 2], [3, 4]]) [2 4] ‫ في‬3 ‫ضرب العدد‬


print(arr * 2) [6 8]] ‫كل عنصر من‬
‫عناصر المضفوفة‬
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [7 8 9]
print(arr2d[2])

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


print(arr2d[0][2]) #3 3 ‫ داخل‬2 ‫العنصر‬
print(arr2d[0, 2]) #3 0 ‫المصفوفة‬
data1 = [6, 7.5, 8, 0, 1] [6. 7.5 8. 0. 1. ]
arr1 = np.array(data1)
print(arr1)
data1 = [6, 7.5, 8, 0, 1] float64 ‫نوع عنصار‬
arr1 = np.array(data1) ‫المصفوفة‬
print(arr1.dtype)
data1 = [6, 7.5, 8, 0, 1] (5,) ‫ مصفوفة‬1
arr1 = np.array(data1) 5 ‫تحتوي على‬
print(arr1.shape) ‫عناصر‬
data1 = [6, 7.5, 8, 0, 1],[3,2,1,9,7] (2,5) ‫ مصفوفة‬2
arr1 = np.array(data1) ‫كل مصفوفة تحتوي‬
print(arr1.shape) ‫ عناصر‬5 ‫على‬
data1 = [6, 7.5, 8, 0, 1],[3,2,1,9,7] 2 ‫ عدد‬ndim
arr1 = np.array(data1) = ‫المصفوفات‬
print(arr1.ndim) ‫مصفوفتين‬
data1 = [6, 7.5, 8, 0, 1] 1
arr1 = np.array(data1)
print(arr1.ndim)
array = np.eye(3) [[1. 0. 0.]
print(array) [0. 1. 0.]
[0. 0. 1.]]
array = np.eye(5) [[1. 0. 0. 0. 0.]
print(array) [0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
array = np.arange(0, 10, 2) [0 2 4 6 8] ‫من صفر الى تسعه‬
print(array) 2 ‫وكل مره نزيد‬
array = np.random.randint(0, 10, (3,3)) [[1 1 5] 3x3‫مصفوفة‬
print(array) [4 3 3] ‫اعداد عشوائية من‬
[7 4 5]] 9 ‫ الى‬0
arr = np.array([[1., 2., 3.], [4., 5., 6.]]) [[0. 0. 0.] ‫طرح مصفوفة من‬
print(arr - arr) [0. 0. 0.]] ‫مصفوفة‬
arr = np.array([[1., 2., 3.], [4., 5., 6.]]) [[ 1. 4. 9.] ‫رفع كل عنصر‬
print(arr **2) [16. 25. 36.]] 2power ‫لالساس‬
arr = np.array([[1., 2., 3.], [4., 5., 6.]]) [[False True False] ‫مقارنة كل عنصر‬
arr2 = np.array([[0., 4., 1.], [7., 2., 12.]]) [ True False True]] ‫من المصفوفة‬
print(arr2 > arr) ‫االولى مع العنصر‬
‫المقابل في‬
‫المصفوفة الثانية‬
arr = np.arange(10) [64 64 64 64 64 64 64 64 64 64]
arr[:] = 64
print(arr)
arr2d = np.array([1, 2, 3]) [1 2] ‫من البداية الى‬
print(arr2d[: -1]) ‫النهاية باستثناء اخر‬
)1-(‫عنصر‬
arr2d = np.array([1, 2, 3]) [1] ‫من البداية الى‬
print(arr2d[: -2]) ‫النهاية باستثناء اخر‬
)-2(‫عنصرين‬
arr = np.array([[1., 2., 3.]]) [1. 2. 3.] ‫طباعة كل العناصر‬
print(arr[-1])
arr = np.array([[1., 2., 3.], [4., 5., 6.]]) [[3.]
print(arr[:, -1:]) [6.]]
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[3] ‫اخر عنصر من كل‬
last_column = arr2d[:, -1:] [6] ‫مصفوفة‬
print(last_column) [9]]
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [1 2 3]
for x in arr2d: [4 5 6]
print(x) [7 8 9]
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [3]
for x in arr2d: [6]
print(x[-1:]) [9]

Multiple-Choice
1. What does np.zeros((2, 3)) return?
a. A 1D array of zeros with 6 elements
b. A 2D array of zeros with 2 rows and 3 columns
c. A scalar value of 0
d. A 3D array of zeros
2. What is the primary difference between a Python list and a NumPy ndarray?
a. Python lists are faster for numerical operations
b. ndarrays require all elements to be of the same type
c. ndarrays do not support slicing
d. Python lists use less memory
3. What is the output of the following code?
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr * arr)
a. [[1, 2, 3], [4, 5, 6]]
b. [[1, 4, 9], [16, 25, 36]]
c. [[2, 4, 6], [8, 10, 12]]
d. An error occurs
4. How do you generate a 3x3 identity matrix in NumPy?
a. np.identity(3)
b. np.eye(3)
c. np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
d. All of the above
5. What is the output of this slicing operation?
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[:, 2])
a. [3, 6, 9]
b. [7, 8, 9]
c. [1, 2, 3]
d. [2, 5, 8]
6. What does numpy.array() function do?
a. Creates a NumPy array from a list
b. Converts a NumPy array to a Python list
c. Computes the sum of elements in an array
d. Reshapes an array
7. What does broadcasting mean in NumPy?
a. Performing matrix multiplication
b. Adding two arrays of different shapes
c. Creating random numbers in an array
d. Reshaping an array
8. Which of the following methods would you use to create a 2x2 matrix of random numbers between 0 and 1?
a. np.random.randint(2, size=(2, 2))
b. np.random.random((2, 2))
c. np.zeros((2, 2))
d. np.ones((2, 2))

9. What is the output of the following code?


a. [3, 4, 5]
b. [1, 2, 3, 2]
c. None
d. [3, 4, 5, 2]
10. Which of the following is NOT a feature of NumPy?
a. Supports multi-dimensional arrays
b. Provides built-in support for mathematical operations
c. Is part of Python's standard library
d. Allows broadcasting for arrays of different shapes
11. What does the following code produce?
a. A flattened version of arr
b. A 1D array with values [1, 2, 3, 4]
c. The transpose of the array arr
d. The inverse of the array arr
12. What will the following code output?
arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4])
a. [1, 2, 3]
b. [2, 3, 4]
c. [1, 2, 3, 4]
d. [2, 3]
13. What will the following code output?
a. [1, 2, 3]
b. [2, 4, 6]
c. [1, 4, 9]
d. Error
CODING
1. Consider the two-dimensional array, arr2d.
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
• Write a code to slice this array to display the last column,
[[3] [6] [9]]
• Write a code to slice this array to display the last 2 elements of middle array,
[5 6]

import numpy as np
# Define the 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Slice to display the last column


last_column = arr2d[:, -1:]
print("Last column:")
print(last_column)

# Slice to display the last 2 elements of the middle array


middle_row_last_two = arr2d[1, -2:]
print("Last 2 elements of the middle array:")
print(middle_row_last_two)
Explanation:

Last Column:

arr2d[:, -1:] slices all rows (:) and selects only the last column (-1:). The result is a 2D array with the last
column as a separate column vector.

Last 2 Elements of the Middle Row:

arr2d[1, -2:] slices the middle row (1) and selects the last two elements (-2:). The result is a 1D array [5,
6].
2. Write a python code to accomplish the following tasks using numpy:
1) Create a 1D NumPy array with values from 0 to 9 and print it.
2) Create a 3x3 NumPy array filled with random values between 0 and 1.
3) Allow user to enter the number of elements for the 1D array and elements then compute the
following:
1. Print all elements in the array.
2. Compute the sum of all elements in the array.
3. Compute the avg of all elements in the array.
4. Slice the array to extract the first two rows.
5. Multiply array with number 3.

import numpy as np

# 1) Create a 1D NumPy array with values from 0 to 9 and print it.


arr = np.arange(10)
print(arr)

# 2)Create a 3x3 NumPy array filled with random values between 0 and 1.
arr = np.random.random((3, 3))
print(arr)

# 2)Create a 3x3 NumPy array filled with random values between 0 and 1.
arr = np.random.random((3, 3))
print(arr)

# 3) Get the number of elements for the 1D array


n = int(input("Enter the number of elements in the array: "))
elements = []
# 3) Get the elements from the user
print("Enter the elements:")
for i in range(n):
x= float(input())
elements.append(x)
# 3) Create a 1D NumPy array
array_1d = np.array(elements)
# 3-1) Print Array
print(array_1d)
# 3-2) Compute the sum of all elements in the array.
sum =0
for x in array_1d:
sum += x
print("SUm= ", sum)

# 3-3) Compute the avg of all elements in the array.


avg = sum / len(array_1d)
print("Avg= ", avg)

# 3-4) Slice the array to extract the first two rows.


sliced = array_1d[:2]
print(sliced)

# 3-5) Multiply array with number 3


array_1d = array_1d * 3
print(array_1d)
3.Write a python code for entering elements into a 2D Array

Input Example:

Output:

import numpy as np

# Get the dimensions of the 2D array


rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))

# Initialize an empty list to store rows


elements = []

print(f"Enter the elements row by row ({rows} rows and {cols} columns):")
for i in range(rows):
row = [float(input(f"Enter element for row {i+1}, column {j+1}: ")) for j in
range(cols)]
elements.append(row)

# Create a 2D NumPy array


array_2d = np.array(elements)
print("2D Array created:")
print(array_2d)

You might also like