This is the second day of my participation in Gwen Challenge

Numpy array slice

The format of the slice is [start:end:step]

import numpy as np

target = np.arange(9).reshape(3.3)

target[:, [0.2]]
Copy the code

Note: the slice is still a slice without end. If you want to express all data, you can use [0:]. Of course, 0 can be omitted. When end is specified as -1 or the last index of the array, end itself is not included.

Also, as the code says, we can pass in the index of a dimension to the list to slice.

Then the output result is

array([[0, 2],
       [3, 5],
       [6, 8]])
Copy the code

Numpy Array index

Use np.ix_ to use a Boolean index on the corresponding dimension

import numpy as np

target = np.arange(9).reshape(3.3)

print(target[np.ix_([True.False.True], [True.False.True])])
target[np.ix_([1.2], [True.False.True]]Copy the code

Then there is output:

[[0 2]
 [6 8]]
array([[3, 5],
       [6, 8]])
Copy the code

The previous code doesn’t help us by writing a list of boilers. the np.ix_ function is a mapping of two arrays to produce a Cartesian product.

import numpy as np

target = np.arange(25).reshape(5, -1)
print(target)
print("*\n")
print(target[np.ix_([2.3], [4.1.3]])Copy the code
[0 12 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] * [[14 11 13] [19 16 18]Copy the code

If you do not use the np.ix_ function, you need to use the following method

print(target[[2.3The [:]], [4.1.3]])
Copy the code

This will be less readable.

Amazing broadcast mechanism!

Scalar and array broadcasts

import numpy as np

res = 4 * np.ones((2.2)) + 1
print(res)
res = 1 / res
res
Copy the code

The output is

[[5. 5.]] Array ([[0.2, 0.2], [0.2, 0.2]])Copy the code

Operations between two-dimensional arrays

If the dimensions of two arrays are exactly the same, the operation can be performed, otherwise an error will be reported, unless one of the arrays has dimensions m × 1 or 1 × n, which will increase the size of its dimension with 1 to the corresponding dimension of the other array. For example, element-by-element operations on 1 × 2 and 3 × 2 arrays expand the first array to 3 × 2, and assign the corresponding value of the row (column) before the expansion. Note that if the dimension of the first array is 1 × 3, then the size in the second dimension does not match and is not 1, then an error is reported.

import numpy as np

res = np.ones((3.2))
res *= np.array([2.3])
print(res)
res *= np.array([[2]])
print(res)
res *= np.array([2])
print(res)
res *= np.array(2)
res
Copy the code

The code above should correct your understanding of dimensions, but the last three arrays are all two-dimensional arrays, row by column, in some sense. It is also natural to go through two of the expansions described above.

How do I navigate between a one-dimensional array and a two-dimensional array?

Why don’t you read the first few lines?