Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is [:,:-1] in python? [duplicate]

Tags:

python

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]
like image 808
afek banyas Avatar asked May 17 '26 13:05

afek banyas


1 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: example

like image 120
Junkrat Avatar answered May 19 '26 02:05

Junkrat