Can someone explain use of [:,-1]

Screen Link:

My Code: <!–’’'testing_probs = pd.DataFrame(columns=unique_origins)

for x in unique_origins:
X_test = test[features]

**testing_probs[x] = models[x].predict_proba(X_test)[:,-1]'**''-->
Replace this line with your code

What I expected to happen:

testing_probs[x] = models[x].predict_proba(X_test)[:,-1]

I need to understand the use of [:,-1]

1 Like

[:, -1] it would give you every last element from second dimension.

In general in python if you provide negative index it will give item from reverse (From right side). So -1 means last element, -2 means second last elements.
For example:

>>> s = "Python"
>>> s[-1]
'n'
>>> s[-2]
'o'

Hi @4jvarun:

for [:,-1] everything before the comma refers to the row you are extracting and everything after denotes the column. This is similar to python slices. In this case the colon : denotes all rows. -1 denotes you are extracting the last column. Do have a review of slices if you are still unfamiliar about this.

Hope this helps!

I suppose I asked it wrongly… What I really needed to know was use of [:,-1] with models.predict_proba(X_test) because when I run the code without [:,-1]; I am getting into an error

For eg : testing_probs = models.predict_proba(X_test)

error : - ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series

Hey @4jvarun,

That’s because you are trying to assign some (a,b) dimension array into the data frame which is not possible. It would be like assigning two or more columns into one. See, “cannot set a frame with”

So [:,-1] gives you a series that can be assigned to the data frame directly.

For example,
This kind of array would be returned and if you try to assign it to one column then there would be an error.

[array([[ 0.8,  0.2],
       [ 0.4,  0.6],
       [ 0.8,  0.2],
       [ 0.9,  0.1],
       [ 0.4,  0.6]])]

After [:,-1], it would be like this,

array([0.2,  0.6,  0.2,  0.1, 0.6]) 

which can be assigned to the data frame.

Hope it clarifies your doubt!!

understood … thanks :relaxed:

2 Likes