This question already has answers here:
Get the position of the largest value in a multi-dimensional NumPy array
(4 answers)
Closed 3 years ago.
I want to print out the index of an array that has the maximum value (and since indexing begins at 0, I need to add one to the index value to get 1-indexed). Example:
rslt = np.amax(final_array)
print("The maximum value is :", rslt)
print("The optimal choice that has that value is :", rslt.index[])
Context: I am writing some multi-criteria decision analysis code in Python. I import numpy to handle arrays of alternatives, criteria and weights. I use np.amax to find the maximum value in the final array.
use numpy.argmax to find the index of the max value.
import numpy as np
#some list
f = [1,2,3,4,5,6,6,6,6,6]
#max value
print (f"the max value is : { np.amax(f)}")
#indices where max values are located
max_indices = np.argwhere( f == np.amax(f))
#adding 1 to get position
max_positions = [i+1 for i in max_indices.flatten().tolist()]
print(f"Max values are located at : {max_positions}")
#first max value
print(f"First max value occurs at : {max_positions[0]}")
Related
This question already has answers here:
Numpy: find index of the elements within range
(12 answers)
How to return indices of values between two numbers in numpy array
(2 answers)
How to conditionally select elements in numpy array
(2 answers)
Closed 1 year ago.
I have the following data lets call it y with the corresponding x values. Plotting plt.plot(x,y) results in: I now want to extract a specific part of that data that is between the x-values of 8.6075 and 8.62. Plotting the part using plt.xlim(8.6075, 8.62) gives the following. I have tried to find the indices using of the x-values using index1=np.where(x==8.6075), index2=np.where(x==8.62) and than just cutting out that specific part of the data using y_cutout = y[index1:index2]. The problem was that the exact values 8.6075 and 9.62 have no indices that they are defined on.
You can find the index of the nearest value by creating a new array of the differences between the values in the original array and the target, then find the index of the minimum value in the new array.
For example, starting with an array of random values in the range 5.0 - 10.0:
import numpy as np
x = np.random.uniform(low=5.0, high=10.0, size=(20,))
print(x)
Find the index of the value closest to 8 using:
target = 8
diff_array = np.absolute(x - target)
print(diff_array)
index = diff_array.argmin()
print(index, x[index])
Output:
[7.74605146 8.31130556 7.39744138 7.98543982 7.63140243 8.0526093
7.36218916 6.62080638 6.18071939 6.54172198 5.76584536 8.69961399
5.83097522 9.93261906 8.21888006 7.63466418 6.9092988 9.2193369
5.41356164 5.93828971]
[0.25394854 0.31130556 0.60255862 0.01456018 0.36859757 0.0526093
0.63781084 1.37919362 1.81928061 1.45827802 2.23415464 0.69961399
2.16902478 1.93261906 0.21888006 0.36533582 1.0907012 1.2193369
2.58643836 2.06171029]
3 7.985439815743841
You can make a selection by following
y_cutout = y[(x >= 8.6075) & (x <= 8.62)]
(Fixed as #AcaNg mentioned in the comment)
With regards to efficiency, how can we create a large numpy array where the values are float numbers within a specific range.
For example, for a 1-D numpy array of fixed size where the values are between 0 and 200,000,000.00 (i.e. values in [0, 200,000,000.00]), I can create the array using the smallest data type for floats (float16) and then validate any new value (from user input) before inserting it to the array:
import numpy as np
a = np.empty(shape=(1000,), dtype=np.float16))
pos = 0
new_value = input('Enter new value: ')
# validate
new_value = round(new_value, 2)
if new_value in np.arange(0.00, 200000000.00, 0.01):
# fill in new value
a[pos] = new_value
pos = pos + 1
The question is, can we enforce the new_value validity (in terms of the already-known minimum/maximum values and number of decimals) based on the dtype of the array?
In other words, the fact that we know the range and number of decimals on the time of creating the array, does this gives us any opportunity to (more) efficiently insert valid values in the array?
I am a bit confused how your code even run because it's not working as it is presented here.
It is also a bit unclear why you want to append new values to an empty array you have created beforehand. Did you meant to fill the created array with the new incoming values instead of appending?
np.arange(0.00, 200000000.00, 0.01)
This line is causing problems as it creates a huge array with values leading to a MemoryError in my environment just to check if the new_value is in a certain range.
Extending my comment and fixing issues with your code my solution would look like
import numpy as np
max_value = 200000000
arr = np.empty(shape=(1000,), dtype=np.float16)
new_value = float(input('Enter new value: ')) # More checks might be useful if input is numeric
# validate
if 0 <= new_value <= max_value:
new_value = round(new_value, 2) # round only if range criterion is fulfilled
arr = np.append(arr, new_value) # in case you really want to append your value
This question already has answers here:
Frequency counts for unique values in a NumPy array
(17 answers)
Closed 4 years ago.
Given an numpy array a, I can use np.unique(a) to generate the unique values included in a. How can I get the count of each unique values included in a?
Since you mentioned np.unique, it accepts a second argument called return_counts:
u, c = np.unique(a, return_counts=True)
c[i] is the corresponding count for u[i].
This question already has answers here:
How to get the index of a maximum element in a NumPy array along one axis
(5 answers)
Closed 4 years ago.
I have a numpy vector of size (N,) which contains integers betwen 1-5 and by using the keras function to_categorical I am constructing the corresponing binary matrix that have size (Nx5). For example if the first value of the vector is 1 then the first row of the array it is (1, 0, 0, 0, 0). How can I do the opposite? By having an array of values (could also double values) to return the index with the highest value? Is there any command that can do that automatically?
As an example my input could be an 2D array with doubles for example one row could be [[0.025, 0.022, 0.58, 0.011, 0.22 ]....] and the result to be for that row [3 ...].
If a is your array, use:
a.argmax(axis=1)
This returns the index of maximum value of each row of the array.
Demo:
>>> a = np.array([[5,2,3],[1,3,1]])
>>> a.argmax(axis=1)
[0 1]
I need to find minimum over all elements from the column which has the maximum column sum.
I do the following things:
Create random matrix
from numpy import *
a = random.rand(5,4)
Then calculate sum of each column and find index of the maximum element
c = a.sum(axis=0)
d = argmax(c)
Then I try to find the minimum number in this column, but I am quite bad with syntax, I know how to find the minimum element in the row with current index.
e = min(a[d])
But how can I change it for columns?
You can extract the minimum value of a column as follows (using the variables you have indicated):
e=a[:,d].min()
Note that using
a=min(a[:,d])
will break you out of Numpy, slowing things down (thanks for pointing this out #SaulloCastro).