You are on page 1of 2

import numpy as np

1) BASICS

# arrys also called tensors (3D+) , vectors (1D array), matrixes (2D array)
# numpy arrays only accepts values of the same type

np.array(list) # creates an array given the list, if list of lists, it is a matrix,


a 2d array and so on
np.zeros((2,4)) # creates an array with 2 rows and 4 columns with 0 values
np.random.random((2,4)) # creates an array with 2 rows and 4 columns with random
values between 0 and 1
np.arange(-3,4) # creates one line array with numbers from -3 to 3 (4 not included)
np.arange(4) # numpy understand it as np.arange(0,4), which means a one row array
from value that starts at 0 and ends at 3
np.arange(-3,4,3) # the third argument is the step... so it goes from -3 to 0 to
3... an array with these 3 values

# Atributes

.shape # shows number of rows and columns

# Methods

.flatten() # flattens a n dimension into a 1D array


.reshape((2,3)) # takes an array with 3 rows and 2 columns and turns into an array
with 2 rows and 3 columns

2) INDEXING, SLICING, SORTING

array[1] # gets the 2nd positioned value in a 1D array


array[1,2] # gets the value in the 2nd row and 3rd column of a 2D array

# if array[1] is passed in a 2d array, it returns the whole 2nd row


# if array[:,1] is passed in a 2d array, it returns the whole 2nd column

array[2:4] # slices a 1D array getting only the 3rd and 4th values eg [0,1,2,3,4]
turns [2,3]
array[2:4, 2:4] # slices a 2D array getting 3rd and 4th row values within the 3rd
and 4th column
array[2:4:2, 2:4:2] # adding a third parameter is the step, in this case will jump
a value

np.sort(array) # sorts the values in ascending order for each row... so small
values first and then higher values at the end of the row
# by default axis=1, but can change axis=0 to sort the columns (directions along
rows are axis 0 and columns are axis 1)
np.sort(array,axis=0) # sort the axis 0 (directions along rows or the column
values) in ascending order

3) FILTERING

# Fancy indexing: creates a boolean mask and then applies it to the array
mask = array % 2 == 0 # will get only even numbers
array[mask] # filters the True values and returns the filtered array
array[array % 2 == 0] # this one-liner also works

# np.where: returns the index of the values


np.where(array % 2 == 0) # returns the index of the values
# np.where can also be used to replace
np.where(array == 0, '', array) # all 0 values will be replaced by ''

4) CONCATENATE, DELETE

np.concatenate((array1, array2)) # concatenates vertically, must have same


dimension in the 'glued' side
np.delete(array,1,axis=0) # deletes 2nd row in the 0 axis, if axis=1, deletes the
2nd column

You might also like