0

Given two lists f=['a','b','c','d'] and g=['a','c'], I can produce [0,2]=indexes(f,g) with

def indexes(f,g):
    return [f.index(x) for x in g]

is there a better way?

Motivation: For a numpy matrix X, I want to extract some columns, so I want to replace pd.DataFrame(X,columns=f)[g].values with X[:,indexes(f,g)].

sds
  • 58,617
  • 29
  • 161
  • 278

1 Answers1

0

You can use np.where after np.1d to get the intersecting indices:

np.where(np.in1d(f,g))
(array([0, 2], dtype=int64),)
yatu
  • 86,083
  • 12
  • 84
  • 139