简体   繁体   中英

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. 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. 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. 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.

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 .

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. 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.

4) There is an incorrect indentation line 11 onwards in your code, but it's probably just an error while pasting.

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)

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