Home > database >  Fast way to access elements of a matrix or pandas dataframe from a list of coordinates
Fast way to access elements of a matrix or pandas dataframe from a list of coordinates

Time:12-30

I would like to select non consecutive elements from a matrix or Pandas DataFrame, where the row and column of each element is given in a list of coordinates:

a=[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]]
coor=[(0,1),(3,4),(1,2)]
myList=[]
for i in range(len(coor)):
    myList.append(a[coor[i][0]][coor[i][1]])
print(myList)

Output:

[1, 19, 7]

This code works, but I asume there are more efficient ways (avoiding for loops) to solve this. Any suggestion?

CodePudding user response:

You can do that using Numpy and list comprehension, which is faster than a for loop:

import numpy as np
a=np.array([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]])
coor=[(0,1),(3,4),(1,2)]
myList=[a[c] for c in coor]
print(myList)

CodePudding user response:

Use np.transpose to transform coor variable:

m = np.array(a)
myList = m[tuple(np.transpose(coor))].tolist()

Output:

>>> myList
[1, 19, 7]

>>> np.transpose(coor)
array([[0, 3, 1],
       [1, 4, 2]])

CodePudding user response:

Check

[np.array(a)[x] for x in coor]
Out[201]: [1, 19, 7]
  • Related