Introduction to the

One of the most important features of NumPy is the ability to manipulate multidimensional arrays, also known as NDARray. We can perform a series of complex mathematical operations based on NDARray.

This article introduces some basic common NDARray operations that you can use for data analysis.

Create ndarray

There are many ways to create Ndarray, we can use NP. random to generate data randomly:

import numpy as np
# Generate some random data
data = np.random.randn(2.3)
data
Copy the code
Array ([[0.0929, 0.2817, 0.769], [1.2464, 1.0072, 1.2962]])Copy the code

In addition to creating them randomly, you can also create them from a list:

Arr1 = np.array(data1)Copy the code
Array ([6., 7.5., 8., 0.Copy the code

Create a multidimensional array from a list:

data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
arr2 = np.array(data2)
Copy the code
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
Copy the code

Create an array with an initial value of 0 using np.zeros:

np.zeros(10)
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
Copy the code

Create a 2-dimensional array:

np.zeros((3, 6))
Copy the code
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]])
Copy the code

Create a 3-dimensional array using empty:

np.empty((2, 3, 2))
Copy the code
array([[[0., 0.],
        [0., 0.],
        [0., 0.]],

       [[0., 0.],
        [0., 0.],
        [0., 0.]]])
Copy the code

Note that empty creates an array with a value of 0. This is not necessarily true. Empty is returned from a random selection of Spaces in memory, and there is no guarantee that there are no values in those Spaces. So after we create arrays with Empty, we also need to initialize them before we use them.

Create an array of range classes using arange:

np.arange(15)
Copy the code
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])
Copy the code

Specify the dtype of the element in the array:

arr1 = np.array([1, 2, 3], dtype=np.float64)
arr2 = np.array([1, 2, 3], dtype=np.int32)
Copy the code

The properties of ndarray

You can obtain the shape of the array using data.shape.

data.shape
(2.3)
Copy the code

Obtain dimension information through nDIM:

arr2.ndim
2
Copy the code

The specific data type can be obtained from data.dtype.

data.dtype
dtype('float64')
Copy the code

Type conversion of elements in NDARray

After you have created an Ndarray of type, you can also convert it:

arr = np.array([1, 2, 3, 4, 5])
arr.dtype
dtype('int64')

float_arr = arr.astype(np.float64)
float_arr.dtype
dtype('float64')
Copy the code

Above we use astype to convert an INT64 ndarRay to a Float64 ndarRay.

If the range of conversion types does not match, truncation is automatically performed:

Arr = np. Array ([3.7, 1.2, 2.6, 0.5, 12.9, 10.1]). Arr astype (np) int32) array ([3, 1, 2, 0, 12, 10], dtype = int32)Copy the code

Notice that we’re cutting off the decimal, not rounding up or down.

The mathematics of NDARray

Arrays can operate on constants as well as arrays:

arr = np.array([[1., 2., 3.], [4., 5., 6.]]) arr * arr array([[ 1., 4., 9.], [16., 25., 36.]]) arr + 10 array([[11., . 12 and 13.], [14, 15, 16.]]) arr - arr array ([[... 0, 0, 0], [... 0, 0, 0]]) 1 / arr array ([[1., 0.5, 0.3333], [0.25, * * 0.5 0.2, 0.1667]]) arr array ([[1., 1.4142, 1.7321], [2., 2.2361, 2.4495]])Copy the code

Arrays can also be compared by the size of each element in the array:

arr2 = np.array([[0., 4., 1.], [7., 2., 12.]])

arr2 > arr

array([[False,  True, False],
       [ True, False,  True]])
Copy the code

The index and sliced

The basic use

Let’s take a look at the basic use of index and slicing. An index is basically used in the same way as an array, to access an element in an array.

Note that the elements in the array returned after slicing are references to elements in the original array. Modifying the array of slicing will affect the original array.

Arange (10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # index access ARR [5] Arr [5:8] = 12 array([0, 1, 2, 3, 4, 12, 12, 12, 8, 8) Arr_slice = ARr [5:8] ARR_slice [1] = 12345 ARR array([0, 1, 2, 3, 4, 12, 12345, 12, 8) arr_slice = ARr [5:8] ARR_slice [1] = 12345 arR array([0, 1, 2, 3, 4, 12, 12345, 12, 8) # 9]) build a two-dimensional array arr2d = np, array ([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) arr2d [2] array ([7, 8, Array ([[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) arr3d array ([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] # index arr3d three-dimensional array [0] array ([[1, 2, 3], [4, 5, 6]] # copy Old_values = arr3D [0]. Copy () ARR3D [0] = 42 ARR3D Array ([[[42, 42, 42], [42, 42, 42]], [[7, 8, 9], [10, 11, 12]]]) arr3d [0] = old_values arr3d array ([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] # index three dimensional array arr3d [1, 0] array([7, 8, 9]) x = arr3d[1] x array([[ 7, 8, 9], [10, 11, 12]]) x[0] array([7, 8, 9])Copy the code

index with slice

Slice can also be used as an index, which denotes an index range value.

Slice, represented as index, can take many forms.

The index starts at 1 and ends at 6-1:

arr[1:6]
Copy the code
array([ 1,  2,  3,  4, 64])
Copy the code

Index starts at 0 and ends at -1:

arr2d[:2]
Copy the code
array([[1, 2, 3],
       [4, 5, 6]])
Copy the code

13. Untidy implies beginning at the beginning and ending with all the data:

arr2d[:2, 1:]
Copy the code
array([[2, 3],
       [5, 6]])
Copy the code
arr2d[1, :2]
Copy the code
array([4, 5])
Copy the code

boolean index

Index can also use a Boolean value to indicate whether to select the data for this index.

Let’s first look at how to build an array of type Boolean:

names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
names == 'Bob'

array([ True, False, False,  True, False, False, False])
Copy the code

Above we return an array of only True and False by comparison.

This array can be accessed as an index value:

Randn (7, 4) array([[0.275, 0.2289, 1.3529, 0.8864], [-2.0016, -0.3718, 1.669, 0.4386], [0.5397, 0.477, 3.2489, 1.0212], [0.5771, 0.1241, 0.3026, 0.5238], [0.0009, 1.3438, 0.7135, 0.8312]. [-2.3702, -1.8608, -0.8608, 0.5601], [-1.2659, 0.1198, -1.0635, 0.3329]] Data [names = = 'Bob'] array ([[0.275, 0.2289, 1.3529, 0.8864], [0.5771, 0.1241, 0.3026, 0.5238]])Copy the code

While indexing rows, you can also index columns:

Data [names == 'Bob', 3] array([0.8864, 0.5238])Copy the code

We can invert it with the ~ sign:

Data [~ (names = = 'Bob')] array ([[2.0016, 0.3718, 1.669, 0.4386], [0.5397, 0.477, 3.2489, 1.0212], [0.0009, 1.3438, 0.7135, 0.8312], [2.3702, 1.8608, 0.8608, 0.5601], [1.2659, 0.1198, 1.0635, 0.3329]])Copy the code

We can set values via Boolean arrays, which is useful in real projects:

Data (data < 0) = 0 array ([[0.275, 0.2289, 1.3529, 0.8864], [0., 0., 1.669, 0.], [0., 0.477, 3.2489, 0.], [0., 0.1241, 0.3026, 0.5238], [0.0009, 1.3438, 0. 0.], [.. 0, 0, 0., 0.5601], [0., 0.1198, 0., 0.3329]])Copy the code
Data [names! = 'Joe'] = 7 array ([[7, 7, 7, 7], [0., 0., 1.669, 0.], [7, 7, 7, 7], [7, 7, 7., 7.], [7, 7, 7, 7], [.. 0, 0, 0., 0.5601], [0., 0.1198, 0., 0.3329]])Copy the code

Fancy indexing

Fancy indexing, also known as Fancy indexing, refers to indexing using an array of integers.

For example, let’s create an 8 * 4 array:

arr = np.empty((8, 4))
for i in range(8):
    arr[i] = i
arr
Copy the code
array([[0., 0., 0., 0.], [1., 1., 1., 1.], [2., 2., 2., 2.], [3., 3., 3., 3.], [4., 4., 4., 4.], [5., 5., 5., 5.], [6., [7., 7., 7.] [7.Copy the code

An array of integers is then used to index the rows in the specified order:

arr[[4, 3, 0, 6]]
array([[4., 4., 4., 4.],
       [3., 3., 3., 3.],
       [0., 0., 0., 0.],
       [6., 6., 6., 6.]])
Copy the code

You can also use negative values to index:

arr[[-3, -5, -7]]
Copy the code
array([[5., 5., 5., 5.],
       [3., 3., 3., 3.],
       [1., 1., 1., 1.]])
Copy the code

Fancy indexes can also be combined:

arr = np.arange(32).reshape((8, 4))
arr
Copy the code
array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, [28, 29, 30, 31]]Copy the code

Above we built an 8 by 4 array.

arr[[1, 5, 7, 2], [0, 3, 1, 2]]
Copy the code
array([ 4, 23, 29, 10])
Copy the code

And then take their first value in column 2, their third value in column 6, and so on. I end up with a 1-dimensional array.

An array of transformation

We can transform arrays of different dimensions, and we can transform arrays of axes.

The 0 method can transform arrays into arbitrary shapes:

arr = np.arange(15).reshape((3, 5))
arr
Copy the code
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
Copy the code

Arrays also provide a T command to swap the axes of arrays:

arr.T
Copy the code
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])
Copy the code

For higher-dimensional arrays, we can use transpose to transpose the axis:

arr = np.arange(16).reshape((2, 2, 4))
arr
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])
        
arr.transpose((1, 0, 2))
Copy the code
array([[[ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[ 4,  5,  6,  7],
        [12, 13, 14, 15]]])
Copy the code

Transpose ((1, 0, 2))

The idea is to switch the x and y axes and leave the z axis unchanged.

0 We’ve 0 0 created a 3-dimensional, 3-axis array above by using the 0 0 method 0 0 Its shape is 2 * 2 * 4.

Let’s take a look at the correspondence:

[0, 1, 2, 3]

(0,1) – [4, 5, 6, 7]

(1,0) – “[8, 9, 10, 11]

(1,1) – “[12, 13, 14, 15]

After conversion:

[0, 1, 2, 3]

[8, 9, 10, 11]

(1,0) – [4, 5, 6, 7]

(1,1) – “[12, 13, 14, 15]

So we get what we got above.

The axis conversion of multidimensional arrays can be complicated, so it’s easy to understand.

It is also possible to swap two axes using SWapaxes, the example above could be rewritten as:

arr.swapaxes(0.1)
Copy the code

This article is available at www.flydean.com/09-python-n…

The most popular interpretation, the most profound dry goods, the most concise tutorial, many tips you didn’t know waiting for you to discover!

Welcome to pay attention to my public number: “procedures those things”, understand technology, more understand you!