April 21, 2021

numpy - Numerical Python - cheatsheet

numpy Package/Library in Python

>>> import numpy as np -- Numerical Python
from numpy import array

numpy arrays cannot contain elements with different types.

array function is to create N-dimensional numpy array.
myarray = np.array([1,2,5,8,4])
two_d_array = np.array([ [3.4, 8.7, 9.9], 
               [1.1, -7.8, -0.7],
               [4.1, 12.3, 4.8]])
x = np.array([0, 100])
a = np.array([24, 12, 57], np.int8)
aapl_dates = np.array(AAPL['date'], dtype=np.datetime64)
array_of_floats = np.array([5.5, 5.4, 4.11, 6.0, 6.2, 5.8, 7.1], float)
my_array = numpy.array(input().split(), float)
A = numpy.array([input().split() for _ in range(N)], int)
array_1 = np.array(tuple_1)
array_2 = np.array(list_2)
array_3 = np.array([list_1, list_2, list_3])

B = np.matrix([input().split() for i in range(n)], dtype=np.int)
num_array = np.asarray([6, 8, 2])
num_array = np.asarray(list4, float)
arr = np.asarray(image_gr)

Printing lements in numpy array/matrices.
two_d_array[1][2]
two_d_array[0, 1]
two_d_array[:, 1:3]
two_d_array[2, :] # 3rd row & all columns
print(array_2d[:, 1])
print(data[343])
x[4, ]
x[:3]
print(data['Survived'])
print(int_array[:-1])
print(int_array[::-1]) # reverse of the array
print(array_1d[[2, 5, 6]])

np.shape(data)
x.size
x.dtype
type(x) # numpy.ndarray
print(myarray.dtype, myarray.ndim)
print("Item size: {}".format(myarray.itemsize))
print(len(np.array(distance_in_kms)))
print("The max in matrix: {0}".format(mat.max()))
print("The max in matrix: {0}".format(mat.max(axis=1))) -- rowwise max number
print("The max in matrix: {0}".format(mat.sum(axis=0))) -- columnwise numbers
print(X.sum())
print(Y.sum(axis = 0))
print numpy.sum(np_array)                   
print numpy.sum(np_array, axis = 0)         
print numpy.sum(np_array, axis = 1)         
print numpy.sum(np_array, axis = None)      
print numpy.prod(np_array, axis = 0)        
print numpy.prod(np_array, axis = 1)        
print numpy.prod(np_array, axis = None)     
print numpy.prod(np_array)         
print(numpy.prod(numpy.sum(A, axis=0), axis=0))

gk_heights = np_heights[np_positions == 'GK']
print(np.array(distance_in_kms)*1000)
dtcon = numpy.vectorized(dt.datetime.fromtimestamp)
for row in array_2d: print(row)

print(myarray.mean())
np.mean(city[:,0])
print(np.median(myarray))
np.median(city[:,0])
np.std(city[:,0])
print numpy.var(my_array, axis = 1)
np.corrcoef(city[:,0], city[:,1])
print(myarray.max()) -- max number
print(myarray.argmax()) -- index of max number
print numpy.min(my_array, axis = 1)
print numpy.max(my_array, axis = 0)
print(myarray > 5.6)
print(np.concatenate(array1, array2))
print numpy.concatenate((array_1, array_2), axis = 1)
print(np.array(array1)+np.array(array2))       -- addition of two arrays
print(any(greater_than))
print(all(greater_than))

arange([start,] stop[, step,], dtype=None) -- like range function, but arange will work with floating point numbers also
ar = np.arange(12)
a = np.arange(1, 10, 4)
x = np.arange(0.5, 10.4, 0.8, int)
y = np.arange(1, len(x)+1) / len(x)
mat = np.arange(30).reshape(5, 6)
array_3d = np.arange(24).reshape(2, 3, 4)
im_sq = np.reshape(im, (28, 28))
array.reshape(4, -1) # -1 means whatever dimension is needed, calculated automatically

linspace(start, stop, num=50, endpoint=True, retstep=False)
print(np.linspace(1, 10))
d = np.linspace(0, 1, 5, endpoint=False)
samples, spacing = np.linspace(1, 10, 20, endpoint=True, retstep=True)

print(np.identity(3))
eye(N, M=None, k=0, dtype=float)
np.eye(5, 8, k=1, dtype=int)
print numpy.eye(8, 7, k = -2)
print(mat.shape)
a=np.ones((4, 4), dtype=int)
print(numpy.ones((3, 3, 3), dtype = numpy.int))
window = np.ones(window_size)/float(window_size)
np.zeros(5)
a = np.zeros((2, 2))
>>> a = np.zeros((7, 7), dtype=np.int)
w = np.zeros([784, 500], np.float32)
print(numpy.zeros((n, m, p), dtype = numpy.int))
np.zeros_like(labels, dtype=bool)
c = np.full((2, 2), 7)

copy(obj, order='K')
y = x.copy()

from numpy.random import randint as ri
height = np.round(np.random.normal(1.65,0.2,6000), 2)
city = np.column_stack((height, weight))
random_mat = np.random.random((2, 2))
np.random.random([3, 4])
A = np.floor(np.random.random((3, 3))*10)
np.random.seed(19840409)
x = mu + sigma * np.random.randn(10000)
inter_nohitter_time = np.random.exponential(tau, 100000)

np.square(cities)
np_vals_log10 = np.log10(np_vals)
print numpy.poly([-1, 1, 1, 10])
print numpy.polyint([1, 1, 1])
print numpy.polyder([1, 1, 1, 1])
print numpy.polyval([1, -2, 0, 2], 4)
np.polyval(arr, p)
print numpy.polyfit([0,1,-1, 2, -2], [0,1,1, 4, 4], 2)
slope, intercept = np.polyfit(votes, share, 1)
print numpy.roots([1, 0, -1])

print(numpy.rint(my_array))
print(numpy.floor(my_array))
print(numpy.ceil(my_array))
TrueNegative = np.logical_and( score <=t, actual==0 ).sum()

np.vstack((array_1, array_2))
np.hstack((array_3, array_4))

print np.add(x, y)
print np.subtract(x, y)
print np.multiply(x, y)
print np.divide(x, y)
np.floor_divide(A,B)
print numpy.mod(a, b)
print numpy.power(a, b) 
print a**b
np.linalg.inv(a) # Inverse
np.linalg.det(a) # Determinant
np.linalg.eig(a) # Eigenvalues and eigenvectors
U, s, VT = np.linalg.svd(data, full_matrices=True)
print numpy.cross(A, B)
vv = np.tile(v, (4, 1))

print numpy.linalg.det([[1 , 2], [2, 1]]) # determinant of an array
print("%0.2f"%numpy.linalg.det(A))
print numpy.linalg.inv([[1 , 2], [2, 1]]) # inverse of a matrix
vals, vecs = numpy.linalg.eig([[1 , 2], [2, 1]])

X_train = X_train[:, np.newaxis]

np.save('x', a)
np.load("x.npy")
Image = np.expand_dims(np.expand_dims(grayim, 0), -1)

np.loadtxt('exam.txt',delimiter=',', unpack=True)
predictors = np.loadtxt('predictors.csv', delimiter='-')
data = np.loadtxt(filename, delimiter=',', skiprows=1)
data = np.loadtxt(filename, delimiter='\t', skiprows=1, usecols=[0,2])   -- import 1 & 3d columns
data = np.loadtxt(filename, delimiter=';', dtype=str)
data_float = np.loadtxt(file, delimiter='\t', dtype=float, skiprows=1)
data = np.genfromtxt('titanic.csv', delimiter=',', names=True, dtype=None)
d = np.recfromcsv(file, delimiter=',', names=True, dtype=None)

numpy.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None)
np.set_printoptions(threshold = 'Nan')
>>> np.set_printoptions(precision=4)
>>> np.set_printoptions(threshold=5)
>>> np.set_printoptions(suppress=True)
numpy.set_printoptions(sign=' ')
>>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
>>> np.set_printoptions(edgeitems=3, infstr='inf', linewidth=75, nanstr='nan', precision=8, suppress=False, threshold=1000, formatter=None)
>>> np.set_printoptions()  # formatter gets reset
>>> eps = np.finfo(float).eps
numpy.set_printoptions(legacy='1.13')

train_accuracy = np.empty(len(neighbors))
rss = np.empty_like(a_vals)
n_bins = np.sqrt(n_data)
x = np.sort(df['share'])
X = np.sort(10 * np.random.rand(30, 1), axis=0)
np.sin(x)
y = np.sin(X).ravel()
y_cos = np.cos(x)
print(np.exp(a))
print(np.log(a))
rss[i] = np.sum((fertility - a*illiteracy - b)**2)
predicted = np.clip(predicted, eps, 1-eps)
np.log(predicted)

Z = X_mat.T # transpose of numpy matrix
print numpy.transpose(my_array)
print my_array.flatten()

print numpy.dot(A, B)
grayim=np.dot(im[...,:3], [0.299, 0.587, 0.114])
vectorDotProduct = np.vdot(vector1, vector2)
innerProduct = np.inner(vector1, vector2)
print(int(numpy.inner(A, B)))

outerProduct = np.outer(vector1, vector2)
print numpy.outer(A, B)
tensorDotProduct = np.tensordot(matrix1, matrix2)
kronProduct = np.kron(matrix1, matrix2)

>>> np.info(optimize.fmin)
>>> np.allclose(svd_mat, arr)

>>> from numpy import poly1d
>>> p = poly1d([3, 4, 5])
>>> print p.integ(k=6)
>>> print p.deriv()

from numpy.distutils.misc_util import Configuration
config = Configuration(None, parent_package, top_path)

from numpy.distutils.core import setup

Related Articles:  scipy package in Python          pandas in Python


No comments:

Post a Comment