简体   繁体   English

比较numpy数组中的元素,并将相等的元素添加到新数组中

[英]Compare elements within a numpy array and add the equal elements to a new array

CSV file I have a numpy array with 907 rows and 2 columns, the columns correspond to x and y coordinates respectively. CSV文件我有一个numpy数组,其中有907行和2列,这些列分别对应于x和y坐标。 I want to write a code that make lists of all the elements that have the same Y. This is my code write now, I know it's wrong. 我想编写一个代码,列出所有具有相同Y的元素。这是我现在编写的代码,我知道这是错误的。 Any help would be really appreciated. 任何帮助将非常感激。

import csv
import numpy as np
with open('Results.csv') as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    integers=np.array([list(map(int,x)) for x in readCSV]);

    val=0
    list_val=[]
    for i in integers:
        if i[1]==val:
        list_val=i   
        val += 1

Trying to answer this with minimum changes to your code. 尝试以最少的代码更改来回答此问题。 There are primarily three issues in your code: 您的代码中主要存在三个问题:

1) You're using val to iterate over all possible values of the Y coordinate, but val doesn't actually take on every possible Y value. 1)您正在使用val遍历Y坐标的所有可能值,但val实际上并没有采用所有可能的Y值。 The code below works assuming that you only ever have non-negative integer Y values, and I've replaced val with max_y to provide a better sense of how to logically iterate over all possible Y coordinate values. 下面的代码在假设您只有非负整数Y值的情况下工作,并且我用max_y替换了val ,以更好地了解如何在逻辑上遍历所有可能的Y坐标值。

2) You'll need two loops: one to iterate over all possible Y values, and the inner loop to iterate over all the X,Y pairs in integers . 2)您将需要两个循环:一个循环遍历所有可能的Y值,以及一个内部循环遍历所有以integers的X,Y对。

3) Since you have multiple possible values for Y, storing elements with the same Y value in a list would mean that you'd need multiple lists to achieve what you're trying. 3)由于您有多个可能的Y值,因此将具有相同Y值的元素存储在列表中将意味着您需要多个列表才能实现所要尝试的功能。 list_val in the code below is a list-of-lists, wherein each inner list is such that the X,Y pairs it stores have the same Y. 下面的代码中的list_val是一个列表列表,其中每个内部列表使得其存储的X,Y对具有相同的Y。

4) There is an incorrect indentation line 11 onwards in your code, but it's probably just an error while pasting. 4)您的代码中的缩进行11不正确,但是粘贴时可能只是错误。

import csv
import numpy as np
with open('this_csv.csv') as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    integers=np.array([list(map(int,x)) for x in readCSV])
    print(integers)
    max_y = np.amax(integers, axis=0)[1]
    list_val=[]
    for i in range(max_y+1):
        this_list = []
        for element in integers:
            if element[1]==i:
                this_list.append(element)
        if len(this_list)>0:
            list_val.append(this_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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