Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Replacing list comprehensions with pandas and numpy Python

The function below uses slices to get the maximum value between 2 indexes at once. So it gets the maximum value between 0 and 10 and then 10 and 12 and such. The function is derived from the answer to this post post. Is there a way I could could replace the list comprehensions in the form of a pandas function like pd.Series(). Or if possible do it as a numpy function.

list_ = np.array([9887.89, 9902.99, 9902.99, 9910.23, 9920.79, 9911.34, 9920.01, 9927.51, 9932.3, 9932.33, 9928.87, 9929.22, 9929.22, 9935.24, 9935.24, 9935.26, 9935.26, 9935.68, 9935.68, 9940.5])
indexes = np.array([0,10,12,14])
chunks = np.split(list_, indexes[1:-1])
MAX=([c.max() for c in chunks])
question from:https://stackoverflow.com/questions/65946986/replacing-list-comprehensions-with-pandas-and-numpy-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would recommend this:

MAX = np.maximum.reduceat(list_,indexes[:-1])

output:

array([9932.33, 9929.22, 9940.5 ])

Another way that will NOT increase your performance and is merely a replacement for list comprehension in your answer (in fact, might even be slightly slower):

max = np.vectorize(np.max)
MAX = max(chunks)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...