Home > Software engineering >  Python: grab subset of array where value of first column is equal to specific value
Python: grab subset of array where value of first column is equal to specific value

Time:09-29

I have a an array like the following

[[1,20,25],[1,45,16],[2,67,81],[3,1,1],[3,23,22]]

I want to create a new array from the first array above but taking only the rows where the value of the first column is 1. How can I loop through the entire array checking if the first column of each row is 1 and then adding that row to a new array so that it will look like the following:

[[1,20,25],[1,45,16]]

CodePudding user response:

Another, not so fancy, way would be this:

arr = [[1,20,25],[1,45,16],[2,67,81],[3,1,1],[3,23,22]]
new_arr = []
for sub_arr in arr:
    # check if the first element in sub_arr is 1
    if sub_arr[0] == 1:
        # if so append it to the new array
        new_arr.append(sub_arr)

print(new_arr)

  • Related