With the help of Numpy matrix.fill() method, we are able to fill a scalar value in a given matrix and gives output as matrix having scalar values.,Example #1 :In this example we can see that with the help of matrix.fill() method we are able to fill the given matrix with a scalar value.,Return : Return a matrix having scalar value,Python | Numpy matrix.fill()
[ [0 0 0] ]
[ [1 1 1] [1 1 1] ]
If you can use NumPy, use fancy indexing into a flattened view of the array and reshape:
In[1]: import numpy as np
In[2]: a = np.zeros(9)
In[3]: a
Out[3]: array([0., 0., 0., 0., 0., 0., 0., 0., 0.])
In[4]: values = [1, 3, 5, 8]
In[5]: a[values] = 1
In[6]: a
Out[6]: array([0., 1., 0., 1., 0., 1., 0., 0., 1.])
In[7]: a.reshape((3, 3))
Out[7]:
array([
[0., 1., 0.],
[1., 0., 1.],
[0., 0., 1.]
])
You can use a list compreehension:
[
[1
if i * 10 + j in values
else 0
for j in range(10)
]
for i in range(10)
]
In this case, I suggest you to create values
as a set.
values = set([1, 3, 5, 8])
All elements of a will be assigned this value.,Fill the array with a scalar value., numpy.matrix.flatten , numpy.matrix.searchsorted
>>> a = np.array([1, 2]) >>> a.fill(0) >>> a array([0, 0]) >>> a = np.empty(2) >>> a.fill(1) >>> a array([1., 1.])
There are two simple ways to fill NumPy arrays. You can fill an existing array with a specific value using numpy.fill(). Alternatively, you can initialize a new array with a specific value using numpy.full(). NumPy also has built-in functions to create and fill arrays with zeros (numpy.zeros()) and ones (numpy.ones()).,We’ll start with a demonstration of how to change all the values in an existing array (numpy.fill()), then move on the to built-in function to initialize arrays with specific values.,Now, let’s fill that array with a specified value using numpy.fill(). Numpy.fill() is a very simple function. It can be called on any NumPy array of any dimension. It takes one argument, the value that will fill all array elements. For example, to fill the array we created with the value 2, use the following line of code.,The array should look similar to the result below. Your values will be slightly different. Again, for a description of creating arrays with NumPy visit my guide. It will explain the creation methods used in this tutorial.
All of the code for this lesson is going to be written as if you were using an interactive console (like the Anaconda prompt, bash, terminal, cmd, etc.). Make sure you have imported NumPy as follows to use the code snippets in this tutorial
import numpy as np
a = np.empty(5)
array([7.56603881e-307, 6.23054972e-307, 6.23053954e-307, 1.02360052e-306, 1.78020984e-306 ])
Your result should match the one below.
array([2., 2., 2., 2., 2.])
To create a 2D array with 5 rows and 5 columns that is filled with -9999, use the following code.
a = np.full((5, 5), -9999)
To create a matrix we can use a NumPy two-dimensional array. In our solution, the matrix contains three rows and two columns (a column of 1s and a column of 2s).,flatten is a simple method to transform a matrix into a one-dimensional array. Alternatively, we can use reshape to create a row vector:,NumPy’s main data structure is the multidimensional array. To create a vector, we simply create a one-dimensional array. Just like vectors, these arrays can be represented horizontally (i.e., rows) or vertically (i.e., columns).,Sparse matrices only store nonzero elements and assume all other values will be zero, leading to significant computational savings. In our solution, we created a NumPy array with two nonzero values, then converted it into a sparse matrix. If we view the sparse matrix we can see that only the nonzero values are stored:
NumPy actually has a dedicated matrix data structure:
matrix_object = np.mat([ [1, 2], [1, 2], [1, 2] ])
matrix_object
=
np
.
mat
([[
1
,
2
],
[
1
,
2
],
[
1
,
2
]])
matrix([ [1, 2], [1, 2], [1, 2] ])
Sparse matrices only store nonzero elements and assume all other values will be zero, leading to significant computational savings. In our solution, we created a NumPy array with two nonzero values, then converted it into a sparse matrix. If we view the sparse matrix we can see that only the nonzero values are stored:
# View sparse matrix print(matrix_sparse)
# View sparse matrix
(
matrix_sparse
)
(1, 1) 1 (2, 0) 3
There are a number of types of sparse matrices. However, in compressed sparse row (CSR) matrices, (1, 1)
and (2, 0)
represent the (zero-indexed) indices of the non-zero values 1
and 3
, respectively. For example, the element 1
is in the second row and second column. We can see the advantage of sparse matrices if we create a much larger matrix with many more zero elements and then compare this larger matrix with our original sparse matrix:
# Create larger matrix matrix_large = np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]) # Create compressed sparse row(CSR) matrix matrix_large_sparse = sparse.csr_matrix(matrix_large)
# View original sparse matrix
(
matrix_sparse
)
(1, 1) 1 (2, 0) 3
(1, 1) 1 (2, 0) 3
# View larger sparse matrix print(matrix_large_sparse)
NumPy’s arrays make that easy:
# Load library import numpy as np # Create row vector vector = np.array([1, 2, 3, 4, 5, 6]) # Create matrix matrix = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) # Select third element of vector vector[2]
# Load library
import
numpy
as
np
# Create row vector
vector
=
np
.
array
([
1
,
2
,
3
,
4
,
5
,
6
])
# Create matrix
matrix
=
np
.
array
([[
1
,
2
,
3
],
[
4
,
5
,
6
],
[
7
,
8
,
9
]])
# Select third element of vector
vector
[
2
]
3
3
# Select second row, second column
matrix[1, 1]
Dimension of the matrix can be defined by passing appropriate value for arguments nrow and ncol.,Matrix can be created using the matrix() function.,It is possible to name the rows and columns of matrix during creation by passing a 2 element list to the argument dimnames.,Dimension of matrix can be modified as well, using the dim() function.
We can check if a variable is a matrix or not with the class()
function.
> a
[, 1][, 2][, 3]
[1, ] 1 4 7[2, ] 2 5 8[3, ] 3 6 9 >
class(a)[1]
"matrix" >
attributes(a)
$dim
[1] 3 3 >
dim(a)[1] 3 3
Providing value for both dimension is not necessary. If one of the dimension is provided, the other is inferred from length of the data.
> matrix(1: 9, nrow = 3, ncol = 3)[, 1][, 2][, 3]
[1, ] 1 4 7[2, ] 2 5 8[3, ] 3 6 9 >
# same result is obtained by providing only one dimension >
matrix(1: 9, nrow = 3)[, 1][, 2][, 3]
[1, ] 1 4 7[2, ] 2 5 8[3, ] 3 6 9
We can see that the matrix is filled column-wise. This can be reversed to row-wise filling by passing TRUE
to the argument byrow
.
> matrix(1: 9, nrow = 3, byrow = TRUE) # fill matrix row - wise[, 1][, 2][, 3] [1, ] 1 2 3[2, ] 4 5 6[3, ] 7 8 9
These names can be accessed or changed with two helpful functions colnames()
and rownames()
.
> colnames(x)[1]
"A"
"B"
"C" >
rownames(x)[1]
"X"
"Y"
"Z" >
# It is also possible to change names
>
colnames(x) < -c("C1", "C2", "C3") >
rownames(x) < -c("R1", "R2", "R3") >
x
C1 C2 C3
R1 1 4 7
R2 2 5 8
R3 3 6 9
Another way of creating a matrix is by using functions cbind()
and rbind()
as in column bind and row bind.
> cbind(c(1, 2, 3), c(4, 5, 6))[, 1][, 2]
[1, ] 1 4[2, ] 2 5[3, ] 3 6 >
rbind(c(1, 2, 3), c(4, 5, 6))[, 1][, 2][, 3]
[1, ] 1 2 3[2, ] 4 5 6
To create and initialize a matrix in python, there are several solutions, some commons examples using the python module numpy:,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[,To create a matrix containing only 0, a solution is to use the numpy function ones,To create a matrix containing only 0, a solution is to use the numpy function zeros
\begin{equation}
A = \left( \begin{array}{ccc}
1&7& 3& 7& 3& 6& 4& 9& 5
\end{array}\right)
\end{equation}
>>>
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)
>>> A.shape(9, )
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)
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)
\begin{equation}
A = \left( \begin{array}{ccc}
0&0& 0& 0& 0& 0& 0& 0& 0&0
\end{array}\right)
\end{equation}
>>> A = np.zeros((10)) >>> A array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) >>> A.shape(10, )