python numpy Library -- Learning

Keywords: Python Machine Learning linear algebra

import numpy as np

Create an empty vector of length 10:

Z = np.zeros(10)
print(Z)

How to find the memory size of any array

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))

Create a vector with a range of 10 to 49

# Z = np.arange(10,50)
# print(Z)

Invert a vector (the first element becomes the last)

 # Z = np.arange(50)
# Z = Z[::-1]
# print(Z)

Create a 3x3 matrix with values from 0 to 8

 # Z = np.arange(9).reshape(3,3)
# print(Z)

The positional index of non-0 elements in array [1,2,0,0,4,0] was found

nz = np.nonzero([1,2,0,0,4,0])

Create a 3x3 identity matrix

# Z = np.eye(3)

Create a two-dimensional array, where the boundary value is 1 and the other values are 0

# Z = np.ones((10,10))
# Z[1:-1,1:-1] = 0

For an existing array, how to add a boundary filled with 0

# Z = np.ones((5,5))
# Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
# print(Z)

Normalize a 5x5 random matrix

# Z = np.random.random((5,5))
# Zmax, Zmin = Z.max(), Z.min()
# Z = (Z - Zmin)/(Zmax - Zmin)
# print(Z)

Create a custom dtype that describes the color as (RGBA) four unsigned bytes

# color = np.dtype([("r", np.ubyte, 1),
#                   ("g", np.ubyte, 1),
#                   ("b", np.ubyte, 1),
#                   ("a", np.ubyte, 1)])
# color

What is the product of a 5x3 matrix multiplied by a 3x2 matrix

# Z = np.dot(np.ones((5,3)), np.ones((3,2)))
# print(Z)

Given a one-dimensional array, negate all elements between 3 and 8

# Z = np.arange(11)
# Z[(3 < Z) & (Z <= 8)] *= -1
# print(Z)

How to round a floating point array from zero

# Z = np.random.uniform(-10,+10,10)
# print (np.copysign(np.ceil(np.abs(Z)), Z))

How to find common elements in two arrays

# Z1 = np.random.randint(0,10,10)
# Z2 = np.random.randint(0,10,10)
# print(np.intersect1d(Z1,Z2))

How to get the date of yesterday, today and tomorrow

# yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
# today     = np.datetime64('today', 'D')
# tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
# print ("Yesterday is " + str(yesterday))
# print ("Today is " + str(today))
# print ("Tomorrow is "+ str(tomorrow))

Create a random vector of length 10 with a range from 0 to 1, but excluding 0 and 1

# Z = np.linspace(0,1,11,endpoint=False)[1:]
# print (Z)

Convert a 10x2 matrix in Cartesian coordinates to polar coordinates

# Z = np.random.random((10,2))
# X,Y = Z[:,0], Z[:,1]
# R = np.sqrt(X**2+Y**2)
# T = np.arctan2(Y,X)
# print (R)
# print (T)

Create a vector with a length of 10 and replace the maximum value in the vector with 1

# Z = np.random.random(10)
# Z[Z.argmax()] = 0
# print (Z)

How to convert a 32-bit floating point number (float) to a corresponding integer (integer)

# Z = np.arange(10, dtype=np.int32)
# Z = Z.astype(np.float32, copy=False)
# print (Z)

Subtract the average of each row in a matrix

 # X = np.random.rand(5, 10)
# # Recent versions of numpy
# Y = X - X.mean(axis=1, keepdims=True)
# print(Y)

How to accumulate the elements of vector (X) to array (F) according to index list (I)

# X = [1,2,3,4,5,6]
# I = [1,3,9,3,4,1]
# F = np.bincount(I,X)
# print (F)

Consider an array of dimensions (5,5,3) and how to multiply it by an array of dimensions (5,5)

# A = np.ones((5,5,3))
# B = 2*np.ones((5,5))
# print (A * B[:,:,None])

How to calculate the average of an array through a sliding window

# def moving_average(a, n=3) :
#     ret = np.cumsum(a, dtype=float)
#     ret[n:] = ret[n:] - ret[:-n]
#     return ret[n - 1:] / n
# Z = np.arange(20)

# print(moving_average(Z, n=3))

How to negate a Boolean value or change the sign of a floating-point number in place

# Z = np.random.randint(0,2,100)
# np.logical_not(Z, out=Z)

How to find the most frequent value in an array

# Z = np.random.randint(0,10,50)
# print (np.bincount(Z).argmax())

For a one-dimensional array X, calculate the average of the 95% confidence interval after it is bootstrapped

# X = np.random.randn(100) # random 1D array
# N = 1000 # number of bootstrap samples
# idx = np.random.randint(0, X.size, (N, X.size))
# means = X[idx].mean(axis=1)
# confint = np.percentile(means, [2.5, 97.5])
# print (confint)

Posted by phpr0ck5 on Thu, 14 Oct 2021 19:10:52 -0700