Sarah111-AHM / Semsmah

2 stars 0 forks source link

😍numpy chatsheat 😍 #9

Open Sarah111-AHM opened 1 year ago

Sarah111-AHM commented 1 year ago

NumPy is the fundamental package for scientific computing in Python

NumPy (Numerical Python) is an open source Python library The NumPy library contains multidimensional array and matrix data structures

ndarray, a homogeneous n-dimensional array object

Installing NumPy

pip install numpy

import NumPy


import numpy as np

difference between a Python list and a NumPy array

Why use NumPy?

NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.

We can access the elements in the array using square brackets. When you’re accessing elements, remember that indexing in NumPy starts at 0. That means that if you want to access the first element in your array


a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])

Output:


[1 2 3 4]

An array is usually a fixed-size container of items of the same type and size.

dimensions are called axes.

create a basic array

np.array(), np.zeros(), np.ones(), np.empty(), np.arange(), np.linspace()

Creating array by np.array

You can create a NumPy array using the np.array() function. Here are a few examples:

Example 1: Creating a 1-D array

import numpy as np

arr1 = np.array([1, 2, 3, 4])
print(arr1)    # Output: [1 2 3 4]

In this example, we create a 1-D array with four elements using the np.array() function and store it in the variable arr1. We then print the array using the print() function.

Example 2: Creating a 2-D array

import numpy as np

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

In this example, we create a 2-D array with two rows and three columns using the np.array() function and store it in the variable arr2. We then print the array using the print() function.

Example 3: Creating an array of zeros

import numpy as np

arr3 = np.zeros((3, 4))
print(arr3)    # Output: [[0. 0. 0. 0.]
               #          [0. 0. 0. 0.]
               #          [0. 0. 0. 0.]]

In this example, we create a 3x4 array of zeros using the np.zeros() function and store it in the variable arr3. We then print the array using the print() function.

Example 4: Creating an array of ones

import numpy as np

arr4 = np.ones((2, 2))
print(arr4)    # Output: [[1. 1.]
               #          [1. 1.]]

In this example, we create a 2x2 array of ones using the np.ones() function and store it in the variable arr4. We then print the array using the print() function.

Creating array by np.empty()