- Что такое функция numpy.zeros() в Python — примеры
- Синтаксис
- Параметры
- Возвращаемое значение
- Примеры программ с методом numpy.zeros() в Python
- Пример 1
- Пример 2
- Пример 3
- numpy.zeros#
- How to Create a Zero Matrix in Python
- How to Create a Zero Matrix in Python
- Python Program to Create a Zero Matrix
- How to create and initialize a matrix in python using numpy ?
- Create a simple matrix
- Create a matrix containing only 0
- Create a matrix containing only 1
- Create a matrix from a range of numbers (using arange)
- Create a matrix from a range of numbers (using linspace)
- Create a matrix of random integers
- Create a matrix of random floats
- Create a matrix of strings
- Create an identity matrix
- References
- Benjamin
Что такое функция numpy.zeros() в Python — примеры
В данном руководстве рассмотрим, что такое функция numpy.zeros() в Python. Она создает новый массив нулей указанной формы и типа данных.
Синтаксис
Параметры
Метод numpy.zeros() принимает три параметра, один из которых является необязательным.
- Первый параметр — это shape, целое число или последовательность целых чисел.
- Второй параметр — datatype, является необязательным и представляет собой тип данных возвращаемого массива. Если вы не определите тип данных, np.zeros() по умолчанию будет использовать тип данных с плавающей запятой.
- Третий параметр — это order, представляющий порядок в памяти, такой как C_contiguous или F_contiguous.
Возвращаемое значение
Функция np zeros() возвращает массив со значениями элементов в виде нулей.
Примеры программ с методом numpy.zeros() в Python
Пример 1
Проблема с np.array() заключается в том, что он не всегда эффективен и довольно громоздок в случае, если вам нужно создать обширный массив или массив с большими размерами.
Метод NumPy zeros() позволяет создавать массивы, содержащие только нули. Он используется для получения нового массива заданных форм и типов, заполненных нулями.
Пример 2
В этом примере мы видим, что после передачи формы матрицы мы получаем нули в качестве ее элемента, используя numpy zeros(). Таким образом, 1-й пример имеет размер 1 × 4, и все значения, заполненные нулями, такие же, как и в двух других матрицах.
В третьей матрице, arr3, все они являются числами с плавающей запятой. Помните, что элементы массива Numpy должны иметь один и тот же тип данных, и если мы не определим тип данных, то функция по умолчанию будет создавать числа с плавающей запятой.
Пример 3
Мы можем создавать массивы определенной формы, указав параметр shape.
numpy.zeros#
Return a new array of given shape and type, filled with zeros.
Parameters : shape int or tuple of ints
Shape of the new array, e.g., (2, 3) or 2 .
dtype data-type, optional
The desired data-type for the array, e.g., numpy.int8 . Default is numpy.float64 .
order , optional, default: ‘C’
Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
like array_like, optional
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
Array of zeros with the given shape, dtype, and order.
Return an array of zeros with shape and type of input.
Return a new uninitialized array.
Return a new array setting values to one.
Return a new array of given shape filled with value.
>>> np.zeros((5,), dtype=int) array([0, 0, 0, 0, 0])
>>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]])
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype array([(0, 0), (0, 0)], dtype=[('x', '
How to Create a Zero Matrix in Python
How to Create a Zero Matrix in Python | Previously we have developed programs to create matrix in Python now, we will discuss how to create a zero matrix in python. Matrix is a rectangular table arranged in the form of rows and columns, in the programming world we implement matrix by using arrays by classifying it as 1D and 2D arrays. In this section, there are some examples to create a zero matrix in python.
How to Create a Zero Matrix in Python
A zero matrix is a matrix that contains all 0 elements. The np.zeros() is a function in NumPy that creates a zero matrix, here dtype is used to specify the data type of the elements.
import numpy as np m = np.zeros([3, 3], dtype=int) print(m)
The above code creates a zero matrix with 3 rows and 3 columns.
Python Program to Create a Zero Matrix
This python program also performs the same task but in different ways. In this program, we will create a zero matrix in python without NumPy.
m, n = 2, 3 matrix = [[0] * n for i in range(m)]
Python Program Examples with Output
- Perfect Square in Python
- Absolute Value in Python
- Simple Calculator in Python
- Fibonacci Series in Python
- Get the ASCII value of Char
- Reverse a Number in Python
- Reverse a Negative Number
- Find Prime Factors in Python
- Get the First Digit of a Number
- Math.factorial() – Math Factorial
- Even Number Python Program
- Odd Number Python Program
- Even Odd Program in Python
- Multiplication Table in Python
- Leap Year Program in Python
- Fibonacci Series using Recursion
- Find Factors of a Number in Python
- Factorial of a Number using Loops
- Factorial in Python using Recursion
- Factorial using User-defined Function
- Difference Between Two Numbers
- Solve Quadratic Equation in Python
- Sum of Digits of a Number in Python
- Find Largest of 3 Numbers in Python
- Sum of N Natural Numbers in Python
- Average of N Numbers in Python
- Find Sum of N Numbers in Python
- Count Number of Digits in a Number
- Find LCM of Two Numbers in Python
- HCF or GCD of 2 Numbers in Python
- Print ASCII Table in Python
- Pandas Divide Two Columns
- Check Vowel or Consonant in Python
- Check Whether Character is Alphabet
- Convert ASCII to Char
- Convert ASCII to String
- Convert String to ASCII
- Hex String to ASCII String
- Decimal to Binary in Python
- Binary to Decimal in Python
- Decimal to Octal in Python
- Octal to Decimal in Python
- Decimal to Hexadecimal in Python
- Hexadecimal to Decimal in Python
- Celsius to Fahrenheit in Python
- Fahrenheit to Celsius in Python
- Convert Celsius to Kelvin in Python
- Celsius to Fahrenheit and Vice-Versa
- Convert Celsius to Fahrenheit using Function
- Celsius to Fahrenheit and Vice-Versa using Function
How to create and initialize a matrix in python using numpy ?
To create and initialize a matrix in python, there are several solutions, some commons examples using the python module numpy:
Create a simple matrix
Create a 1D matrix of 9 elements:
>>> import numpy as np
>>> A = np.array([1,7,3,7,3,6,4,9,5])
>>> A
array([1, 7, 3, 7, 3, 6, 4, 9, 5])
Notice: the shape of the matrix A is here (9,) and not (9,1)
it is then useful to add an axis to the matrix A using np.newaxis (ref):
>>> A = A[:, np.newaxis]
>>> A
array([[1],
[7],
[3],
[7],
[3],
[6],
[4],
[9],
[5]])
>>> A.shape
(9, 1)
Create a matrix of shape (3,3):
>>> A = np.array([[4,7,6],[1,2,5],[9,3,8]])
>>> A
array([[4, 7, 6],
[1, 2, 5],
[9, 3, 8]])
>>> A.shape
(3, 3)
Another example with a shape (3,3,2)
>>> A = np.array([[[4,1],[7,1],[6,1]],[[1,1],[2,1],[5,1]],[[9,1],[3,1],[8,1]]])
>>> A
array([[[4, 1],
[7, 1],
[6, 1]],
[[1, 1],
[2, 1],
[5, 1]],
[[9, 1],
[3, 1],
[8, 1]]])
>>> A.shape
(3, 3, 2)
Create a matrix containing only 0
To create a matrix containing only 0, a solution is to use the numpy function zeros
>>> A = np.zeros((10))
>>> A
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> A.shape
(10,)
>>> A = np.zeros((3,3))
>>> A
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> A.shape
(3, 3)
Create a matrix containing only 1
To create a matrix containing only 0, a solution is to use the numpy function ones
>>> A = np.ones((10))
>>> A
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
>>> A.shape
(10,)
>>> A = np.ones((3,3))
>>> A
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
>>> A.shape
(3, 3)
Create a matrix from a range of numbers (using arange)
To create a matrix from a range of numbers between [1,10[ for example a solution is to use the numpy function arange
>>> A = np.arange(1,10)
>>> A
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Another example with a step of 2
>>> A = np.arange(1,10,2)
>>> A
array([1, 3, 5, 7, 9])
>>> A = np.arange(1,20,5)
>>> A
array([ 1, 6, 11, 16])
>>> A.shape
(4,)
It is then possible to reshape the matrix:
>>> A = A.reshape(2,2)
>>> A
array([[ 1, 6],
[11, 16]])
>>> A.shape
(2, 2)
Create a matrix from a range of numbers (using linspace)
To create 20 numbers between [1,10[ a solution is to use the numpy function linspace
>>> A = np.linspace(1,10,20)
>>> A
array([ 1. , 1.47368421, 1.94736842, 2.42105263,
2.89473684, 3.36842105, 3.84210526, 4.31578947,
4.78947368, 5.26315789, 5.73684211, 6.21052632,
6.68421053, 7.15789474, 7.63157895, 8.10526316,
8.57894737, 9.05263158, 9.52631579, 10. ])
>>> A.shape
(20,)
Create a matrix of random integers
To create a matrix of random integers, a solution is to use the numpy function randint. Example with a matrix of size (10,) with random integers between [0,10[
>>> A = np.random.randint(10, size=10)
>>> A
array([9, 5, 0, 2, 0, 6, 6, 6, 5, 5])
>>> A.shape
(10,)
Example with a matrix of size (3,3) with random integers between [0,10[
>>> A = np.random.randint(10, size=(3,3))
>>> A
array([[2, 4, 7],
[7, 5, 4],
[0, 9, 4]])
>>> A.shape
(3, 3)
Example with a matrix of size (3,3) with random integers between [0,100[
>>> A = np.random.randint(100, size=(3,3))
>>> A
array([[83, 51, 95],
[74, 7, 70],
[49, 18, 8]])
Create a matrix of random floats
>>> A = A * 0.01
>>> A
array([[ 0.83, 0.51, 0.95],
[ 0.74, 0.07, 0.7 ],
[ 0.49, 0.18, 0.08]])
>>> type(A)
>>> A.dtype
dtype('float64')
Create a matrix of strings
Example of how to create a matrix of strings
>>> A = np.array(('Hello','Hola','Bonjour'))
>>> A
array(['Hello', 'Hola', 'Bonjour'],
dtype='
>>> A.dtype
dtype('
Note: the element type is here ('[HTML REMOVED] 7
>>> A[0] = 'How are you ?'
>>> A
array(['How are', 'Hola', 'Bonjour'],
dtype='
it will be truncated. To fix that a solution is to change the type first:
>>> A = A.astype(' >>> A[0] = 'How are you ?'
>>> A
array(['How are you ?', 'Hola', 'Bonjour'], dtype='
Create an identity matrix
To create an identity matrix a solution is to use the numpy function identity:
>>> import numpy as np
>>> I = np.identity(3)
>>> I
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
References
Links | Site |
---|---|
numpy.chararray | scipy doc |
numpy.random.randint | docs.scipy |
numpy.arange | docs.scipy |
numpy.random.choice | docs.scipy |
numpy.empty | docs.scipy |
numpy.linspace | docs.scipy |
initialize a numpy array | stackoverflow |
How do I create character arrays in numpy? | stackoverflow |
How can I add new dimensions to a Numpy array? | stackoverflow |
numpy.identity | numpy doc |
Benjamin
Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.