Python numpy series detailed tutorial [getting started from zero] - Chapter 2 basic operation of numpy

Numpy The column contains this content
3 articles 1 subscription

1. Method of generating array

1.1 generate an array of 0 and 1

  • np.ones(shape, dtype)

    Generate an array whose results are all 1
    Shape: array shape dimension
    Dtype: array type
  • np.ones_ like(a, dtype)

    The generated result is an array of 1, and the shape is consistent with a
    a: Ndarray object
    Dtype: array type
  • np.zeros(shape, dtype)

    Generate an array with 0 results
  • np.zeros_ like(a, dtype)

    Generate an array with 0 results

Examples are as follows:

  1. Generate a ndarray two-dimensional array with 4 rows and 8 columns and all values are 1.
ones =np.ones([four,eight])

Return result:

array([[one., one., one., one., one., one., one., one.],
       [one., one., one., one., one., one., one., one.],
       [one., one., one., one., one., one., one., one.],
       [one., one., one., one., one., one., one., one.]])
  1. Generate a two-dimensional array of ndarray whose values are 0 consistent with the shape of the ones object.
np.zeros_ like(ones)

Return result:

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.]])

1.2 generate from existing arrays

1.2.1 generation method

  • np.array(object, dtype)

  • np.asarray(a, dtype)

a =np.array([[one,two,three],[four,five,six]])
#Create from an existing array
a1 =np.array(a)
#Equivalent to the form of an index, there is no real creation of a new one
a2 =np.asarray(a)

1.2.2 differences between array and asarray

Insert picture description here

1.3 generate fixed range array

1.3.1 np.linspace (start, stop, num, endpoint)

  • Create an isometric array - specify the number
  • Parameters:
    • Start: the starting value of the sequence
    • Stop: the end value of the sequence
    • Num: the number of equally spaced samples to be generated. The default value is 50
    • Endpoint: whether the sequence contains the stop value. The default value is true
#Generate equally spaced arrays
np.linspace(0, one hundred, eleven)

Return result:

array([  0.,  ten.,  twenty.,  thirty.,  forty.,  fifty.,  sixty.,  seventy.,  eighty.,  ninety., one hundred.])

1.3.2 np.arange(start,stop, step, dtype)

  • Create an isometric array - specify the step size
  • Parameters
    • Step: step size. The default value is 1
np.arange(0, one hundred, five)

Return result:

array([ 0,  five, ten, fifteen, twenty, twenty-five, thirty, thirty-five, forty, forty-five, fifty, fifty-five, sixty, sixty-five, seventy, seventy-five, eighty, eighty-five, ninety, ninety-five])

1.3.3 np.logspace(start,stop, num)

  • Create an isometric sequence with a base of 10
  • Parameters:
    • Num: the number of proportional series to be generated. The default value is 50
#Generate 10 ^ x
np.logspace(0, two, three)

Return result:

array([  one.,  ten., one hundred.])

1.4 generating random arrays

1.4.1 normal distribution

  1. What is normal distribution?
    Normal distribution is a probability distribution. The normal distribution has two parameters μ and σ Distribution of continuous random variables, first parameter μ Is the mean value of random variables subject to normal distribution, the second parameter σ Is the standard deviation of this random variable, so the normal distribution is recorded as n( μ,σ )。

  2. Application of normal distribution
    The probability distribution of many random variables in life, production and scientific experiments can be approximately described by normal distribution, such as the height of all students in a school class.

  3. Normal distribution characteristics
    μ Determines its position and its standard deviation σ Determines the magnitude of the distribution μ = 0 σ = The normal distribution at 1 is the standard normal distribution.

Normal distribution creation method

  • np.random.normal(loc=0.0, scale=1.0, size=None)

    • loc:float

    The mean value of this probability distribution (corresponding to the center of the whole distribution)

    • scale:float

    The standard deviation of this probability distribution (corresponding to the width of the distribution, the larger the scale, the fatter, and the smaller the scale, the thinner)

    • size:int or tuple of ints

    The output shape is none by default, and only one value is output

Example 1: the average height of boys aged 18-30 in China is 1.75 and the standard deviation is 1. 100000000 sample data were collected.

Then, 100000000 normal distribution data with mean value of 1.75 and standard deviation of 1 can be generated.

#Generate uniformly distributed random numbers
x1 =np.random.normal(one point seven five, one, one hundred million)

#Draw a picture to see the distribution
#1) create canvas
plt.figure(figsize=(twenty, ten),dpi=one hundred)

#2) draw histogram
plt.hist(x1, one thousand)

#3) display image

The drawn image is as follows:
Insert picture description here

Example 2: randomly generate the daily increase data of four stocks for one week
How to obtain the weekly (5-day) fluctuation data of 4 stocks?

We can simulate and generate the data of the rise and fall of a group of stocks, and randomly generate the rise and fall in a normal distribution, such as mean 0 and variance 1.

Creation of stock fluctuation data:

#Create 5-day rise and fall data of 4 stocks in line with normal distribution
stock_change =np.random.normal(0, one, (four, five))

Return result:

array([[-zero point four seven five seven one eight five two, -zero point five four three five five two eight five,  zero point three one five nine five two six two, -one point four four nine four one eight two seven, -zero point zero seven one one five two eight two],
       [ zero point nine one six six nine five five eight, -zero point seven eight four five one three seven one, -zero point five six five seven nine three eight seven,  zero point one two nine three nine four nine two, -one point five one seven two eight eight nine seven],
       [-zero point two one eight one one one four six, -one point five three seven five four five three four,  zero point six eight one three three six five one,  zero point seven two nine four one six zero two,  zero point eight two zero four one zero seven eight],
       [-zero point five one six three six three two nine,  one point four eight six two two four zero five,  one point one five one one seven eight one five,  one point six seven nine seven nine four six one,  zero point three seven zero three nine two eight seven]])

1.4.2 uniform distribution

  • np.random.uniform(low=0.0, high=1.0, size=None)
    • Function: randomly sample from a uniform distribution [low, high]. Note that the definition domain is closed on the left and open on the right, that is, it contains low and does not contain high
    • Parameter introduction:
      • Low: sampling lower bound, float type, the default value is 0;
      • High: sampling upper bound, float type, the default value is 1;
      • Size: the number of output samples, which is of type int or tuple. For example, if size = (m, N, K), MNK samples will be output, and 1 value will be output by default.
    • Return value: ndarray type, whose shape is consistent with that described in the parameter size.

Example: randomly generate 100 million numbers from - 1 to 1.

#Generate uniformly distributed random numbers
x2 =np.random.uniform(-one, one, one hundred million)

Draw a picture to see the distribution:

importmatplotlib.pyplot asplt

#Generate uniformly distributed random numbers
x2 =np.random.uniform(-one, one, one hundred million)

#Draw a picture to see the distribution
#1) create canvas
plt.figure(figsize=(ten, ten),dpi=one hundred)

#2) draw histogram
plt.hist(x=x2,bins=one thousand)  #X represents the data to be used, and bins represents the number of intervals to be divided

#3) display image

Insert picture description here
It can be seen from the histogram drawn by the above code that if the interval from - 1 to 1 is divided into 1000, then the generated 100 million numbers, and the number of numbers distributed in each interval is approximately 100000. This belongs to uniform distribution.

2. Index and slice of array

How to index one-dimensional, two-dimensional and three-dimensional arrays?

  • Direct indexing, slicing
  • Object [:,:] – first and last columns

Two dimensional array index method:

  • For example: obtain the rise and fall data of the first stock generated in the above code in the first three trading days
#Two dimensional array, two dimensions
stock_change[0, 0:three]

Return result:

array([-zero point four seven five seven one eight five two, -zero point five four three five five two eight five,  zero point three one five nine five two six two])

3. Shape modification

3.1 ndarray.reshape(shape, order)

  • Returns a view with the same data field but different shapes
  • Rows and columns are not interchangeable
#When converting shapes, be sure to pay attention to the element matching of the array
stock_change.reshape([five, four])
stock_change.reshape([-one,ten])  #The shape of the array is modified to: (2, 10), - 1: indicates that it passes through the to be calculated

3.2 ndarray.resize(new_shape)

  • Modify the shape of the array itself (keep the number of elements the same before and after)
  • Rows and columns are not interchangeable
stock_change.resize([five, four])
#View modified results
(five, four)

3.3 ndarray.T

  • Transpose of array
  • Exchange the rows and columns of the array
(four, five)

4. Type modification and array de duplication

4.1 ndarray.astype(type)

  • Returns the array after the type is modified

The modified type is converted to np.int32.

4.2 np.unique()

temp =np.array([[one, two, three, four],[three, four, five, six]])
array([one, two, three, four, five, six])

Creation is not easy, white whoring is not good. Your support and recognition is the biggest driving force for my creation. See you in the next article!

Dragon youth

If there are any mistakes in this blog, please comment and advice. Thank you very much!
Insert picture description here

  • 0
    give the thumbs-up
  • 0
  • 0
  • One key three links
    One key three links
  • Sweep and share posters

Insert expression
©️ 2020 CSDN Skin theme: swimming - white Designer: Bai Songlin Return to home page
Paid inelement
Payment with balance
Click retrieve
Code scanning payment
Wallet balance 0

Deduction Description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted according to the ratio of 1:1.
2. The balance cannot be purchased and downloaded directly. You can buy VIP, c-coin package, paid column and courses.

Balance recharge