2

I am new in Python. I want to slice columns from index 1 to end of a marix and perform some operations on the those sliced out columns. Following is the code:

import numpy as np
import pandas as pd

train_df = pd.read_csv('train_475_60_W1.csv',header = None) 
train = train_df.as_matrix()
y = train[:,0]
X = train[:,1:-1]

The problem is if I execeute "train.shape", it gives me (89512, 61). But when I execute "X.shape", it give me (89512, 59). I was expecting to get 60 as I want to execute operations on all the colunms except the first one. Can anyone please help me in solving this?

3
  • don't you want X = train[:,1:]? with slicing here the end slice isn't included which is not what you want Commented Jul 7, 2017 at 7:42
  • "From index 1 to end of a matrix" is train[:,1:], not train[:,1:-1] Commented Jul 7, 2017 at 7:43
  • @EdChum Thanks! That's the info I was missing! Commented Jul 7, 2017 at 13:58

2 Answers 2

3

In the line

X = train[:,1:-1] 

you cut off the last column. -1 refers to the last column, and Python includes the beginning but not the end of a slice - so lst[2:6] would give you entries 2,3,4, and 5. Correct it to

X = train[:,1:] 

BTW, you can make your code format properly by including four spaces before each line (you can just highlight it and hit Ctrl+K).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks...for both the suggestions! It's working now!
3

The thing you should know with slicing for single dimension even in normal lists is that it looks like this:

[start : end]

with start included and end excluded.

you can also use these:

[:x] # from the start to x
[x:] # from x to the end

you can then generalize than to 2D or more, so in your case it would be:

X = train[:,1:] # the first : to get all rows, and 1: to get all columns except the first

you can learn more about these in here if you want, it's a good way to practice

2 Comments

Thanks...I didn't know that Python doesn't include the last column in slicing! It's working Great! Thanks for the tutorial link!!
No problem at all, don't forget to accept the answer that suited you most as a sign for future users who might see this question ;) @SumaiyaIqbal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.