python - 如何在矩阵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
感谢您的帮助。我希望我解释得很好。
解决方案
我的朋友。
你的帮助就在这里。
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]
再见。
推荐阅读
- java - Testng XmlSuite.getAllParameters() 抛出 NullPointerException
- php - Laravel 5.6 - 工厂关系无限播种
- java - 不要从 http 重定向到 https
- json - node.js - 从变量中获取 JSON 键的名称
- javascript - 为什么当代码有效时 JQuery .val() 方法有时会返回 undefined?
- excel - 自动边界单元格
- jsf - Primefaces fileUpload 未被调用
- javascript - 非常基本的示例 - 启用或禁用按钮
- python - 访问当前架构上下文
- excel - 预期语句结束 VBA 错误