What Is [: ,: -1] in Python? [Duplicate]

What Is [: ,: -1] in Python? [Duplicate]

I just started learning ML myself in python. I didn't understand a passage in the code and would be happy if you made it clear to me what he was saying. Plus I don't know what [:, -1] and [:,: - 1] do

inputs = training_data[:,:-1]
outputs = training_data[:, -1]
9

2 Answers

[:, :] literally means [all rows, all columns].

Indexing in python starts from 0 when you go from the first element to the last, but it starts from -1 when you start from the last element.

So, when you do [:, -1] it means you are taking all the rows and only the last column. -1 represents the last column.

When you do [:, :-1], it means you are taking all the rows and all the columns except the last column.

Now, when you do training_data[:, -1] it means from the dataframe training_date, you are using all the rows and only the last column. Similarly training_data[:, :-1] means all the rows and all the columns except the last column.

But:

You might run into a slicing problem if you do training_data[:, -1]. Since you are using integers to slice the df, it is always better to use the .iloc method.

This tutorial How do I select multiple rows and columns from a pandas DataFrame? explains everything clearly. Have a look at it.

example:

Check this out:

x = np.random.rand(3,2)
x
array([[0.55424444, 0.86283166],
       [0.11931308, 0.43853805],
       [0.13662337, 0.06383871]])
n = x[:, -1]
n
array([0.86283166, 0.43853805, 0.06383871])
James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.