Data book - Numpy Flashcards
How do you make a 2x3x2 empty np array?
np.empty((2,3,2))
What is np’s equivalent to the range function?
Np.arange(n)
Out: array([0, 1, 2, …, n])
How do you take an existing array a and make a new array with the same shape but all 1’s?
Np.ones_like(a)
How do you make a square n x n matrix?
Np.eye(n)
How do you change an np dtype from one type to another?
array_to_change.astype(dtype)
E.g
a = np.array([‘1’]) a = a.astype(np.float64)
Does slicing an ndarray copy that section and return the copy, or zoom into that section?
Zoom in
How do you make a copy of an ndarray slice?
arr = np.array([…])
barr = arr[5:8].copy()
How do you select the top-left most element of the 2d array arr2d?
arr2d[0,0]
How do you generate randomly distributed data 7 rows by 4 columns?
Np.random.randn(7, 4)
How do you do both a boolean and an array slice in one line?
data[names==‘Bob’, 2:]
How do you select everything except ‘Bob’ in an ndarray?
names != ‘Bob’
Or
data[-(names == ‘Bob’)]
How do you use and/or logic in ndarray slicing?
Mask = (names == ‘Bob’) |/& (names == ‘Will’)
What is fancy indexing?
Indexing with integer arrays
E.g arr[4, 3, 0, 6] pops out those rows in that order
Say you call arr[[1, 5, 7, 2], [0, 3, 1, 2]] on a big 2D ndarray. What happens?
Outputs a 1D array with elements selected by [[rows], [columns]] in the input.
How do you convert two 1D ndarrays to an indexer that selects a square region?
arr[np.ix_([], [])]