Pythonic way to find maximum value and its index in a list?
There are many options, for example:
import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))
How to find the index of the max value in a list for Python?
- You are trying to find the index of
i
. It should belist_c[i]
.
Easy way/Better way is:
idx_max = i
. (Based on @Matthias comment above.)
- Use
print
to print the results and notreturn
. You usereturn
inside functions. - Also your code doesn't work if
list_c
has all negative values because you are settingmax_val
to0
. You get a 0 always.
list_c = [-14, 7, -9, 2]
max_val = 0
idx_max = 0
for i in range(len(list_c)):
if list_c[i] > max_val:
max_val = list_c[i]
idx_max = i
print(list_c, max_val, idx_max)
[-14, 7, -9, 2] 7 1
How to find all positions of the maximum value in a list?
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
How can I get the index of max values in list and then print the values from another list with max's index?
events = [1, 2, 3, 4, 5, 6, 7]
durations = [1, 2, 3, 100, 4, 5, 100]
max_duration = max(durations)
longest_events = (str(event) for event, duration in zip(events, durations)
if duration == max_duration)
print(f"The longest event time is {max_duration}, for the event(s): {','.join(longest_events)}")
Returning the index of max value in a list considering another list as a allowed index in python
Use the key
argument for max
:
max(a,key = lambda i: b[i]) #3
Getting the index of the returned max or min item using max()/min() on a list
if is_min_level:
return values.index(min(values))
else:
return values.index(max(values))
Python, finding the max value of an array above a specific value and it's index
We can find by:
- Finding list of indexes in sequence which are above threshold
- Finding max of values in these indexes
Code
import pandas as pd
import numpy as np
def find_max(a, lower_bound):
' Finds max above threshold '
# Find indexes which are above threshold
valid_idx = np.where(a >= lower_bound)[0]
if valid_idx.size > 0:
# Find maximum from these indexes
max_idx = valid_idx[a[valid_idx].argmax()]
return max_idx, a[max_idx] # return index and max value
Test
data = [(1, 1), (2, 0), (10, 2), (5, 0)]
df = pd.DataFrame(data, columns = ['a','b'])
print("DataFrame\n", df)
print()
# Find max in each column of DataFrame above lower bound
lower_bound = 8
for (column_name, column_data) in df.iteritems():
found_max = find_max(column_data, lower_bound)
if found_max:
print(f'Column {column_name}: max index {found_max[0]}, max_value: {found_max[1]}')
else:
print(f'Column {column_name}: No max found')
Output
DataFrame
a b
0 1 1
1 2 0
2 10 2
3 5 0
Column a: max index 2, max_value: 10
Column b: No max found
How to find max value and its index in a row of 2d list?
as suggested in comments you can use max to get the max values from your list and argmax for getting the position.
np.argmax(q_table, axis=1) #returns list of position of max value in each list.
np.max(q_table, axis=1) # return list of max value in each list.
you can then use zip function to iterate both the list together and store the output in list of list
import numpy as np
max_list_with_position=[ [x,y] for x,y in zip(np.argmax(q_table, axis=1),np.max(q_table, axis=1))]
print(max_list_with_position)
output:
[[2, 0.61], [1, 0.79], [3, 0.93], [2, 0.61], [3, 0.69]]
Related Topics
Cast String to Float Is Not Supported in Linear Model
How to Print Colored Text to the Terminal
How to Print Just the First Letters of Each Word
Python: How to Calculate the Average Word Length in a Sentence Using the .Split Command
Get All Rows That Have Same Value in Pandas
Django.Db.Utils.Operationalerror: (1045, Access Denied for User '<User>'@'Localhost'
Open() Gives Filenotfounderror/Ioerror: Errno 2 No Such File or Directory
Convert Np.Array of Type Float64 to Type Uint8 Scaling Values
Interactive Matplotlib Figures in Google Colab
Adding Months to a Pandas Object in Python
Python: Searching for Common Values in Two Files
How to Download Multiple Files or an Entire Folder from Google Colab
How to Change Default Python Version
How to Code My Bot to Generate Random Images from One Command
Python Check If Website Exists