简体   繁体   中英

Quick comparison of numpy array elements, greater or less than each other

I'm currently implementing clustering algorithms in python. As the end product will be using thousands of array elements I'm attempting to minimize looping and optimize it as much as possible initially.

I'm using scipy's cdist to create a 2D array of distances from a chosen number of random clusters. So 3 clusters would produce an array of distances, say for x points:

distances = array([[5.5,2.5,7.3],
                    [1.0,4.6,2.2],
                    [6.0,2.8,7.1],
                    [5.3,4.6,1.5],
                     ...........]])

Where each column is the distance from a cluster and each row is a point, I wish to quickly create an array of values 0,1 or 2, (with possible solution to identical distances occurring) like so:

label = array([1,0,1,2,.......])

A quick solution, other than looping would be appreciated.

Use

distances.argmin(axis=1)

which returns

array([1, 0, 1, 2])

for your example array.

For identical distances it returns the first occurrence of such element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM