You'll have to test for the type, or use exception handling, to switch approaches:
def find_max(a):
if isinstance(a, list):
return max(list)
return a.values.max()
or
def find_max(a):
try:
return a.values.max()
except AttributeError:
# assume a Python sequence
return max(a)
Which one you pick depends on a few factors:
- Do you need to support other iterables, like tuples or sets or generators?
- What is the more common case; the
try...exceptcase is faster if the majority of calls pass in a Pandas series.
Another option is to use np.max(), which works on either type:
import numpy as np
def find_max(a):
return np.max(a)
Note that there is no need to use the .values attribute here!
You'll have to test for the type, or use exception handling, to switch approaches:
def find_max(a):
if isinstance(a, list):
return max(list)
return a.values.max()
or
def find_max(a):
try:
return a.values.max()
except AttributeError:
# assume a Python sequence
return max(a)
Which one you pick depends on a few factors:
- Do you need to support other iterables, like tuples or sets or generators?
- What is the more common case; the
try...exceptcase is faster if the majority of calls pass in a Pandas series.
Another option is to use np.max(), which works on either type:
import numpy as np
def find_max(a):
return np.max(a)
Note that there is no need to use the .values attribute here!
def find_max(a):
if isinstance(a, list):
return max(a)
elif isinstance(a, pd.DataFrame):
return a.values.max()
else:
print("No max method found for the input type")
how to get the maximum value from a specific portion of a array in python - Stack Overflow
Does nim have an equivalent to python's max function?
python max() in java
min() vs 'sort() and then list[0]'
As others have mentioned, min will be quicker. min just has to walk through the list once, whereas sort must do more compares, making it more complex.
However, one case you might want to use sort is when you need more than just the minimum. Eg. you want the 5 smallest items, not just the smallest. Here "sorted(mylist)[:5]" will do the job, but another option to keep in mind is the heapq module, as "heapq.nsmallest(5, mylist)" will often perform better than sort, at least for a small number of items.
Videos
First slice your list and then use index on the max function:
searchArray = [10,20,30,40,50,60,100,80,90,110]
slicedArray = searchArray[3:9]
print slicedArray.index(max(slicedArray))+3
This returns the index of the sliced array, plus the added beginSlice
Try this...Assuming you want the index of the max in the whole list -
import numpy as np
searchArray = [10,20,30,40,50,60,100,80,90,110]
start_index = 3
end_index = 8
print (np.argmax(searchArray[start_index:end_index+1]) + start_index)