Vector in python example
- Numpy | Array Creation
- numpy.arange() in Python
- numpy.zeros() in Python
- Create a Numpy array filled with all ones
- numpy.linspace() in Python
- numpy.eye() in Python
- Creating a one-dimensional NumPy array
- How to create an empty and a full NumPy array?
- Create a Numpy array filled with all zeros | Python
- How to generate 2-D Gaussian array using NumPy?
- How to create a vector in Python using NumPy
- Python | Numpy fromrecords() method
- Copy and View in NumPy Array
- How to Copy NumPy array into another array?
- Appending values at the end of an NumPy array
- How to swap columns of a given NumPy array?
- Insert a new axis within a NumPy array
- numpy.hstack() in Python
- numpy.vstack() in python
- Joining NumPy Array
- Combining a one and a two-dimensional NumPy Array
- Python | Numpy np.ma.concatenate() method
- Python | Numpy dstack() method
- Splitting Arrays in NumPy
- How to compare two NumPy arrays?
- Find the union of two NumPy arrays
- Find unique rows in a NumPy array
- Python | Numpy np.unique() method
- numpy.trim_zeros() in Python
- Matrix manipulation in Python
- numpy matrix operations | empty() function
- numpy matrix operations | zeros() function
- numpy matrix operations | ones() function
- numpy matrix operations | eye() function
- numpy matrix operations | identity() function
- Adding and Subtracting Matrices in Python
- Matrix Multiplication in NumPy
- Numpy ndarray.dot() function | Python
- NumPy | Vector Multiplication
- How to calculate dot product of two vectors in Python?
- Multiplication of two Matrices in Single line using Numpy in Python
- Python | Numpy np.eigvals() method
- How to Calculate the determinant of a matrix using NumPy?
- Python | Numpy matrix.transpose()
- Python | Numpy matrix.var()
- Compute the inverse of a matrix using NumPy
- Reshape NumPy Array
- Python | Numpy matrix.resize()
- Python | Numpy matrix.reshape()
- NumPy Array Shape
- Change the dimension of a NumPy array
- numpy.ndarray.resize() function – Python
- Flatten a Matrix in Python using NumPy
- numpy.moveaxis() function | Python
- numpy.swapaxes() function | Python
- Python | Numpy matrix.swapaxes()
- numpy.vsplit() function | Python
- numpy.hsplit() function | Python
- Numpy MaskedArray.reshape() function | Python
- Python | Numpy matrix.squeeze()
- Random sampling in numpy | ranf() function
- Random sampling in numpy | random() function
- Random sampling in numpy | random_sample() function
- Random sampling in numpy | sample() function
- Random sampling in numpy | random_integers() function
- Random sampling in numpy | randint() function
- numpy.random.choice() in Python
- How to choose elements from the list with different probability using NumPy?
- How to get weighted random choice in Python?
- numpy.random.shuffle() in python
- numpy.random.geometric() in Python
- numpy.random.permutation() in Python
- Numpy | Array Creation
- numpy.arange() in Python
- numpy.zeros() in Python
- Create a Numpy array filled with all ones
- numpy.linspace() in Python
- numpy.eye() in Python
- Creating a one-dimensional NumPy array
- How to create an empty and a full NumPy array?
- Create a Numpy array filled with all zeros | Python
- How to generate 2-D Gaussian array using NumPy?
- How to create a vector in Python using NumPy
- Python | Numpy fromrecords() method
- Copy and View in NumPy Array
- How to Copy NumPy array into another array?
- Appending values at the end of an NumPy array
- How to swap columns of a given NumPy array?
- Insert a new axis within a NumPy array
- numpy.hstack() in Python
- numpy.vstack() in python
- Joining NumPy Array
- Combining a one and a two-dimensional NumPy Array
- Python | Numpy np.ma.concatenate() method
- Python | Numpy dstack() method
- Splitting Arrays in NumPy
- How to compare two NumPy arrays?
- Find the union of two NumPy arrays
- Find unique rows in a NumPy array
- Python | Numpy np.unique() method
- numpy.trim_zeros() in Python
- Matrix manipulation in Python
- numpy matrix operations | empty() function
- numpy matrix operations | zeros() function
- numpy matrix operations | ones() function
- numpy matrix operations | eye() function
- numpy matrix operations | identity() function
- Adding and Subtracting Matrices in Python
- Matrix Multiplication in NumPy
- Numpy ndarray.dot() function | Python
- NumPy | Vector Multiplication
- How to calculate dot product of two vectors in Python?
- Multiplication of two Matrices in Single line using Numpy in Python
- Python | Numpy np.eigvals() method
- How to Calculate the determinant of a matrix using NumPy?
- Python | Numpy matrix.transpose()
- Python | Numpy matrix.var()
- Compute the inverse of a matrix using NumPy
- Reshape NumPy Array
- Python | Numpy matrix.resize()
- Python | Numpy matrix.reshape()
- NumPy Array Shape
- Change the dimension of a NumPy array
- numpy.ndarray.resize() function – Python
- Flatten a Matrix in Python using NumPy
- numpy.moveaxis() function | Python
- numpy.swapaxes() function | Python
- Python | Numpy matrix.swapaxes()
- numpy.vsplit() function | Python
- numpy.hsplit() function | Python
- Numpy MaskedArray.reshape() function | Python
- Python | Numpy matrix.squeeze()
- Random sampling in numpy | ranf() function
- Random sampling in numpy | random() function
- Random sampling in numpy | random_sample() function
- Random sampling in numpy | sample() function
- Random sampling in numpy | random_integers() function
- Random sampling in numpy | randint() function
- numpy.random.choice() in Python
- How to choose elements from the list with different probability using NumPy?
- How to get weighted random choice in Python?
- numpy.random.shuffle() in python
- numpy.random.geometric() in Python
- numpy.random.permutation() in Python
Векторы в Python
В простом смысле вектор можно рассматривать, как одномерный массив. Что касается Python, вектор – это одномерный массив списков. Он занимает элементы таким же образом, как и список Python.
Давайте теперь разберемся с созданием вектора в Python.
Создание вектора
Модуль NumPy в Python используется для создания вектора. Мы используем метод numpy.array() для создания одномерного массива, то есть вектора.
Пример 1: горизонтальный вектор.
import numpy as np lst = [10,20,30,40,50] vctr = np.array(lst) vctr = np.array(lst) print("Vector created from a list:") print(vctr)
Vector created from a list: [10 20 30 40 50]
Пример 2: вертикальный вектор.
import numpy as np lst = [[2], [4], [6], [10]] vctr = np.array(lst) vctr = np.array(lst) print("Vector created from a list:") print(vctr)
Vector created from a list: [[ 2] [ 4] [ 6] [10]]
Основные операции с вектором
Создав вектор, давайте теперь выполним некоторые базовые операции с этими векторами!
Вот список основных операций, которые можно выполнять с вектором:
- сложение;
- вычитание;
- умножение;
- деление;
- скалярное произведение и т.д.
1. Выполнение операции сложения в векторе
Ниже мы выполнили операцию сложения векторов над векторами. Операция сложения будет выполняться element-wise manner, т.е. поэлементно, и, кроме того, результирующий вектор будет иметь такую же длину, что и два аддитивных вектора.
import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,2,3,4,5] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_add = vctr1+vctr2 print("Addition of two vectors: ",vctr_add)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 2 3 4 5] Addition of two vectors: [11 22 33 44 55]
2. Выполнение вычитания двух векторов
Аналогичным образом, при вычитании также будет применяться поэлементный метод, и в дальнейшем элементы вектора 2 будут вычитаться из вектора 1.
Давайте посмотрим на его реализацию.
import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,2,3,4,5] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_sub = vctr1-vctr2 print("Subtraction of two vectors: ",vctr_sub)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 2 3 4 5] Subtraction of two vectors: [ 9 18 27 36 45]
3. Выполнение умножения двух векторов
При умножении вектора элементы вектора 1 умножаются на элементы вектора 2, а вектор произведения имеет ту же длину, что и векторы умножения.
Попробуем представить себе операцию умножения:
x = [10,20] и y = [1,2] — два вектора. Таким образом, вектор произведения будет v [],
v [0] = x [0] * y [0] v [1] = x [1] * y [1]
Взгляните на приведенный ниже код:
import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,2,3,4,5] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_mul = vctr1*vctr2 print("Multiplication of two vectors: ",vctr_mul)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 2 3 4 5] Multiplication of two vectors: [ 10 40 90 160 250]
4. Выполнение операции деления
При делении результирующий вектор является значениями частного после выполнения операции деления над двумя векторами.
Для лучшего понимания рассмотрим приведенный ниже пример.
x = [10,20] и y = [1,2] – два вектора. Таким образом, результирующий вектор v будет таким:
v [0] = x [0] / y [0] v [1] = x [1] / y [1].
Давайте теперь реализуем вышеуказанную концепцию.
import numpy as np lst1 = [10,20,30,40,50] lst2 = [10,20,30,40,50] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_div = vctr1/vctr2 print("Division of two vectors: ",vctr_div)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [10 20 30 40 50] Multiplication of two vectors: [ 1 1 1 1 1 ]
5. Векторное точечное произведение
В векторном скалярном произведении мы поэлементно производим суммирование произведения двух векторов.
вектор c = x. у = (х1 * у1 + х2 * у2)
import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,1,1,1,1] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_dot = vctr1.dot(vctr2) print("Dot product of two vectors: ",vctr_dot)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 1 1 1 1] Dot product of two vectors: 150