목록Numpy (57)
Note
How to create row numbers grouped by a categorical variable? # Input: url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' species = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4) np.random.seed(100) species_small = np.sort(np.random.choice(species, size=20)) species_small array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Ir..
How to generate one-hot encodings for an array in numpy? # Input: np.random.seed(101) arr = np.random.randint(1,4, size=6) arr # output array([2, 3, 2, 2, 2, 1]) # Solution: def one_hot_encodings(arr): uniqs = np.unique(arr) out = np.zeros((arr.shape[0], uniqs.shape[0])) for i, k in enumerate(arr): out[i, k-1] = 1 return out one_hot_encodings(arr) # output array([[ 0., 1., 0.], [ 0., 0., 1.], [ ..
How to convert an array of arrays into a flat 1d array? # Input: arr1 = np.arange(3) arr2 = np.arange(3,7) arr3 = np.arange(7,10) array_of_arrays = np.array([arr1, arr2, arr3]) print('array_of_arrays: ', array_of_arrays) # Solution 1 arr_2d = np.array([a for arr in array_of_arrays for a in arr]) # Solution 2: arr_2d = np.concatenate(array_of_arrays) print(arr_2d) # output [0 1 2 3 4 5 6 7 8 9]
How to compute the row wise counts of all possible values in an array? # Input: np.random.seed(100) arr = np.random.randint(1,11,size=(6, 10)) arr # output array([[ 9, 9, 4, 8, 8, 1, 5, 3, 6, 3], [ 3, 3, 2, 1, 9, 5, 1, 10, 7, 3], [ 5, 2, 6, 4, 5, 5, 4, 8, 2, 2], [ 8, 8, 1, 3, 10, 10, 4, 3, 6, 9], [ 2, 1, 8, 7, 3, 1, 9, 3, 6, 2], [ 9, 2, 6, 5, 3, 9, 4, 6, 1, 10]]) # Solution def counts_of_all_val..
How to get the positions of top n values from a numpy array? # Input np.random.seed(100) a = np.random.uniform(1,50, 20) # 1 print(a.argsort()) # output [18 7 3 10 15] # 2 np.argpartition(-a, 5)[:5] # output [15 10 3 7 18] # Below methods will get you the values. # 1: a[a.argsort()][-5:] # 2: np.sort(a)[-5:] # 3: np.partition(a, kth=-5)[-5:] # 4: a[np.argpartition(-a, 5)][:5]