import numpy as np print(np.__version__) # Similarities between lists and NumPy 1-D arrays # Both are mutable, indexable, and sliceable numbers = np.array([5,6,7,8]) numbers[1] = 13 print(numbers) print(numbers[-3:]) # Both are iterable for num in numbers: print(num) # Find length using len() print(len(numbers)) # Check membership using in/not in print(13 in numbers) print(14 in numbers) # Arrays can contain only a single object type # Check using .dtype numbers = np.array([5,6,7,8]) print(numbers.dtype) print(numbers.astype(str)) # Unlike lists, arrays preserve scientific notation print([3.5e9,1.4e-3]) print(np.array([3.5e9,1.4e-3])) # NumPy has append() [note different syntax], insert(), delete(), flip() functions # but no option to remove, pop (as with lists) numbers = [5,6,7,8] # list version numbers.append([9,10]) print(numbers) numbers = np.array([5,6,7,8]) # array version numbers = np.append(numbers,[9,10]) print(numbers) # Convert between lists and arrays my_list = [5,6,7,8] my_array = np.array(my_list) my_list1 = my_array.tolist() my_list2 = list(my_array) # Adding lists concatenates them, while adding arrays actually adds them! a = [1,2,3,4] b = [5,6,7,8] print(a + b) a = np.array([1,2,3,4]) b = np.array([5,6,7,8]) print(a + b) a = np.array([1,2,3,4]) b = np.array([5,6,7,8]) print('a + b =',a + b) print('a - b =',a - b) print('a * b =',a * b) print('a + 10 =',a + 10) print('10 * a =',10 * a) print('a / 10 =',a / 10) print('a**2 =',a**2) x = np.array([1,2,3]) y = np.array([11,12,13,14,15]) # print(x + y) # this will produce an error u = np.array([1,2,3,4]) v = np.array([0,2,4,6]) print(u == v) print(u < v) print(v != 0) print(v <= 4) bool1 = np.array([True,False,True]) bool2 = np.array([True,False,False]) print(np.logical_and(bool1,bool2)) print(np.logical_or(bool1,bool2)) v = np.array([10,11,12,13]) print(v[3]) print(v[[2,3]]) print(v[v >= 12]) print(v[[False,False,True,True]]) print(np.where(v >= 12)) print(np.where(v >= 12)[0]) x = np.array([10,11,12,13]) # two ways of applying functions to arrays (or lists) print(np.sum(x)) print(x.sum()) # mathematical reductions print(np.sum(x)) print(np.mean(x)) print(np.median(x)) print(np.max(x)) print(np.min(x)) print(np.std(x)) # constants print(np.pi) print(np.e) print(np.inf) print(np.nan) print(5 * np.inf) print(5 * np.nan) # mathematical element-wise functions print(np.absolute([-2,-1])) print(np.round([5.23,5.29],1)) print(np.sqrt([9,16])) # same as y**0.5 print(np.exp([0,1,2])) print(np.sin([0,np.pi/2])) # argument: angles in radians print(np.cos([np.pi,2*np.pi])) # functions to create new arrays print(np.zeros(4)) print(np.ones(4)) print(np.full(4,2)) print(np.arange(4)) print(np.arange(0,1,0.25)) print(np.linspace(0,1,5))