InquilineKea
InquilineKea

Reputation: 891

How do I select components from a particular list of indices of a Python vector?

So here I have x1vals:

>>> x1Vals
[-0.33042515829906227, -0.1085082739900165, 0.93708611747433213, -0.19289496973017362, -0.94365384912207761, 0.43385903975568652, -0.46061140566051262, 0.82767432358782367, -0.24257307936591843, -0.1182761514447952, -0.29794617763330011, -0.87410892638408, -0.34732294121174467, 0.40646145339571249, -0.64082861589870865, -0.45680189916940073, 0.4688889876175073, -0.89399689430691298, 0.53549621114138612]

And here is the list of x1Vals indices that I want to select

>>> np.where(np.dot(XValsOnly,newweights) > 0)

>>>(array([ 1,  2,  4,  5,  6,  8,  9, 13, 15, 16]),)

But when I try to get the values of x1Vals the Matlab way, I get this error:

>>> x1Vals[np.where(np.dot(XValsOnly,newweights) > 0)]

Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    x1Vals[np.where(np.dot(XValsOnly,newweights) > 0)]
TypeError: list indices must be integers, not tuple
>>> np.where(np.dot(XValsOnly,newweights) > 0)

Is there a way around this?

Upvotes: 2

Views: 599

Answers (1)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58885

The problem is that your x1Vals is a list object, which does not support fancy indexing. You just have to build an array out of it:

x1Vals = np.array(x1Vals)

and your approach will work.

A faster approach would be to use np.take:

np.take(x1Vals, np.where(np.dot(XValsOnly,newweights) > 0))

Upvotes: 1

Related Questions