목록Numpy (57)
Note
How to replace all values greater than a given value to a given cutoff? # Input np.set_printoptions(precision=2) np.random.seed(100) a = np.random.uniform(1,50, 20) # 1: Using np.clip np.clip(a, a_min=10, a_max=30) # 2: Using np.where print(np.where(a 30, 30, a))) # output [ 27.63 14.64 21.8 30. 10. 10. 30. 30. 10. 29.18 30. 11.25 10.08 10. 11.77 30. 30. 10. 30. 14.43]
How to find the position of the first occurrence of a value greater than a given value? # Input: url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris = np.genfromtxt(url, delimiter=',', dtype='object') # Solution: (edit: changed argmax to argwhere. Thanks Rong!) np.argwhere(iris[:, 3].astype(float) > 1.0)[0] # output 50
How to find the most frequent value in a numpy array? # Input: url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris = np.genfromtxt(url, delimiter=',', dtype='object') # Solution: vals, counts = np.unique(iris[:, 2], return_counts=True) print(vals[np.argmax(counts)]) # output b'1.5'
How to sort a 2D array by a column # Sort by column position 0: SepalLength print(iris[iris[:,0].argsort()][:20]) [[b'4.3' b'3.0' b'1.1' b'0.1' b'Iris-setosa'] [b'4.4' b'3.2' b'1.3' b'0.2' b'Iris-setosa'] [b'4.4' b'3.0' b'1.3' b'0.2' b'Iris-setosa'] [b'4.4' b'2.9' b'1.4' b'0.2' b'Iris-setosa'] [b'4.5' b'2.3' b'1.3' b'0.3' b'Iris-setosa'] [b'4.6' b'3.6' b'1.0' b'0.2' b'Iris-setosa'] [b'4.6' b'3.1..
How to get the second largest value of an array when grouped by another array? # Import iris keeping the text column intact url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris = np.genfromtxt(url, delimiter=',', dtype='object') # Solution # Get the species and petal length columns petal_len_setosa = iris[iris[:, 4] == b'Iris-setosa', [2]].astype('float') # Get t..