Home  >  Article  >  Backend Development  >  How to assign uniform values ​​to array elements in numpy

How to assign uniform values ​​to array elements in numpy

php中世界最好的语言
php中世界最好的语言Original
2018-04-09 15:59:035894browse

This time I will show you how to assign uniform values ​​to array elements in numpy, and what are the precautions for assigning uniform values ​​to array elements in numpy. The following is a practical case, let's take a look.

The overall array assignment operation in Numpy has always been a bit confusing to me, and I often don’t understand it deeply. Today I will list the relevant knowledge points separately and summarize them.

Let’s look at two small examples of code snippets:

Example 1:

In [2]: arr =np.empty((8,4))
In [3]: arr
Out[3]:
array([[ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.]])
In [4]: arr[1] = 1
In [5]: arr
Out[5]:
array([[ 0., 0., 0., 0.],
    [ 1., 1., 1., 1.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.],
    [ 0., 0., 0., 0.]])

Example 2:

In [6]: arr1 =np.empty(2)
In [8]: arr1
Out[8]:array([ 7.74860419e-304,  7.74860419e-304])
In [9]: arr1 = 0
In [10]: arr1
Out[10]: 0

These two paragraphs seem to have behavior inconsistent, but in fact the use is generally The object-oriented tag understanding model can still be understood.

In Example 1, the label after adding index actually refers to the specific storage area, while in Example 2, a label is used directly. So how to achieve the overall assignment of a one-dimensional array? In fact, you only need to index all elements.

The specific method is as follows:

In [11]: arr1 =np.empty(2)
In [12]: arr1
Out[12]: array([0., 0.])
In [13]: arr1[:]
Out[13]: array([0., 0.])
In [14]: arr1[:] =0
In [15]: arr1
Out[15]: array([0., 0.])

It seems quite simple, but without doing a slightly in-depth analysis , it is indeed a little difficult to understand.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How Python Numpy operates arrays and matrices

How to merge Python’s numpy arrays

The above is the detailed content of How to assign uniform values ​​to array elements in numpy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn