首页 > 解决方案 > 如何在矩阵numpy中找到前N个不同的行

问题描述

大家好,我有这个,我想优化它。我的问题是在矩阵中取前 N 个不同的行。

            while i<self.K: #self.K is the number of rows that i have to take
            find=False #
            for line in self.centroids: #centroids is the matrix where i will save the different numbers
                c=np.equal(line,self.X[j]) #X is a matrix with all element size (4800,3)
                if np.all(c)==True:
                    find=True  
            if find==False:
                self.centroids[i]=self.X[j]

                i=i+1

            j=j+1

感谢您的帮助。我希望我解释得很好。

标签: pythonpython-3.xmatrixfindartificial-intelligence

解决方案


我的朋友。

你的帮助就在这里。

import numpy as np
import pandas as pd

#  CREATES A TEST ARRAY, WITH SOME RANDOM DATA.
numbers = np.random.rand(20, 1)

#  CREATES A DATAFRAME WITH RANDOM DATA.
df = pd.DataFrame(numbers, columns=['number']) 

#  THIS IS A MAP FUNCTION TO HELP WITH INTEGER VALUES.
def do_integer(param):
    return round(abs(10 * param))

#  HERE I CREATE A COLUMN WITH INTEGER DATA. 
df['integer_number'] = df['number'].map(do_integer)

#  HERE THE CODE YOU NEED. 
n = 4
uniques = []
for item in df.iterrows():
    if item[1]['integer_number'] not in uniques:
        uniques.append(item[1]['integer_number'])
        n = n - 1
        if n == 0:
            break


或者,您可以使用 unique() 方法。好多了...

#  HERE I GET THE TOP 4 UNIQUE ELEMENTS.
n = 4
unique_values = (df['integer_number'].unique())[0:n]

再见。


推荐阅读