NumPy data analysis foundation: basic operations of ndarray array operations and slice index iteration

Table of contents

foreword

1. Basic Mathematical Operations

1. Addition and subtraction

2. Power

3. Conditional filtering

4. Matrix element multiplication

5. Matrix Multiplication

6. Array type implicit conversion

2. Slice indexing and iteration

1. One-dimensional array

2. Multidimensional arrays

Pay attention, prevent getting lost, if there are any mistakes, please leave a message for advice, thank you very much



foreword

As one of the three giants of data analysis, Pandas, matplotlib, and NumPy, it is necessary to give a separate explanation for the face. NumPy application scenarios are very broad, and many Pandas functions are converted to NumPy array data structures. It is even more frequently used than Pandas in machine learning, deep learning, and some data processing operations. Moreover, NumPy is powerful and convenient to use, and supports a variety of complex operations. I usually use NumPy in my Pandas and some machine learning articles, but the blog content does not explain the operation of NumPy in detail, nor does it record some specific function answers about the operation of NumPy. It is really inappropriate for a blogger like me who pursues one-stop service needs, so I will fill up the old pit and publish a new one-text speed learning series-Numpy data analysis basic column.

This series of articles will be included in my column one, a series of fast learning - NumPy data analysis foundation, which basically covers the use of NumPy data to analyze daily business and routine mathematical modeling analysis and complex operations. I will spend a lot of time and thought on creating from basic array operations to complex operations such as processing matrix and vector features, as well as professional NumPy common functions. If you need to engage in data analysis or data development, mathematical modeling, Friends of Python engineering recommend subscribing to the column, and you will learn the most practical and common knowledge in the first time. This blog is long and worth reading and practicing. I will pick out the best part and talk about practice in detail. Bloggers will maintain blog posts for a long time. If you have any mistakes or doubts, you can point them out in the comment area. Thank you for your support.

This chapter mainly explains the basic mathematical operations of the numpy array object ndarray, such as the matrix array operations of addition, subtraction, multiplication and division, and general and commonly used mathematical functions.


1. Basic Mathematical Operations

Arithmetic operators on arrays are performed element-wise, creating a new array and filling it with the result.

1. Addition and subtraction

a = np.array([20, 30, 40, 50])
b = np.arange(10,50,10)
c=a-b
c

 

2. Power

a**2

 

3. Conditional filtering

a<40

 

 Unlike many matrix languages, the product operator * operates on elements in NumPy arrays. The matrix product can be performed using the @ operator (in python versions >= 3.5) or the dot function or method:

4. Matrix element multiplication

A = np.array([[1, 2],
              [3, 4]])
B = np.array([[5, 6],
              [7, 8]])
A*B

 

5. Matrix Multiplication

A@B

 

Or using the dot function is the same:

A.dot(B)

 

 Certain operations, such as += and *=, modify existing arrays, not create new ones.

a = np.ones((2, 3), dtype=int)
a*=3
a

 

a = np.ones((2, 3), dtype=int)
b = np.zeros((2, 3), dtype=int)
b += a
b

 

6. Array type implicit conversion

When operating with arrays of different types, the type of the resulting array corresponds to a more general or precise type (a behavior called upcasting).

a = np.ones((2, 3), dtype=int)
b = np.zeros((2, 3), dtype=float)
c=a+b
c.dtype.name

 

 Many unary operations, such as computing the sum of all elements in an array, are implemented as methods of the ndarray class.

c.sum()
c.max()
c.min()

 By default, these operations are applied to the array as if it were a list of numbers, regardless of its shape. However, operations can be applied along the specified axis of the array by specifying the axis parameter:

b = np.arange(12).reshape(3, 4)
b

 

b.sum(axis=0)

 

b.min(axis=1)

 

b.cumsum(axis=1)

2. Slice indexing and iteration

1. One-dimensional array

One-dimensional arrays can be indexed, sliced, and iterated over, just like lists and other Python sequences.

a=np.arange(10,20,2)
a[2]

 

a[2:5]

 

2. Multidimensional arrays

Each axis of a multidimensional array can have an index. These indices are given as comma-separated tuples:

def f(x, y):
    return 10 * x + y
b = np.fromfunction(f, (5, 4), dtype=int)
b

 

b[2, 3]

 

b[0:5, 1] 

 

b[1:3, :]

 

When fewer indices than the number of axes are provided, the missing indices are treated as complete slices:

b[-1]

 

Expressions within parentheses in b[i] are treated as i , followed by as many instances of : as needed to represent the remaining axesNumPy also allowswriting with dots like b[i,...] .

Dots (...) represent any colons needed to generate the full index tuple. For example, if x is an array with 5 axes, then

  • x[1,2,…] is equivalent to x[1,2,:,:,]
  • x[…,3] to x[:,:,::,:3]
  • x[4,...,5,:] to x[4,:,:,5,:]
c = np.array([[[  0,  1,  2],  
               [ 10, 12, 13]],
              [[100, 101, 102],
               [110, 112, 113]]])
c

 

c[1, ...]

 

c[..., 2]

 

Iterate over a multidimensional array over the first axis:

for row in b:
    print(row)

 

 However, if you want to perform an operation on each element in the array, you can use the flat property, which is an iterator over all elements of the array:

for element in b.flat:
    print(element)

Pay attention, prevent getting lost, if there are any mistakes, please leave a message for advice, thank you very much

That's all for this issue. I'm fanstuck, if you have any questions, feel free to leave a message to discuss, see you in the next issue

 

Guess you like

Origin blog.csdn.net/master_hunter/article/details/127144925