The editor below will share with you an example of unified assignment of array elements in numpy. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor and take a look.
The overall array processing and assignment operation in Numpy has always made me a little confused, and many times I 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 inconsistent behavior. In fact, it can still be understood using the general object-oriented label understanding model.
In Example 1, the label after adding the index actually refers to the specific storage area, while in Example 2, a label is used directly. So how to implement 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 like It's quite simple, but without some in-depth analysis, it is indeed a little difficult to understand.
Related recommendations:
A brief discussion on several sorting methods of numpy arrays_python
Simple example of numpy array splicing_ python
The above is the detailed content of Example of uniform assignment of array elements in numpy. For more information, please follow other related articles on the PHP Chinese website!