我是Python的新手。我想从索引1到的末尾对列进行切片,并对这些切片列执行一些操作。以下是守则:
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]问题是,如果我去掉"train.shape",它会给我(89512,61)。但是当我执行"X.shape“时,它会给我(89512,59)。我希望得到60,因为我想在所有colunm上执行操作,除了第一个colunm。有人能帮我解决这个问题吗?
发布于 2017-07-07 07:42:31
排在队伍里
X = train[:,1:-1] 你切断了最后一列。-1指最后一列,Python包含切片的开头而不是结尾-因此lst[2:6]将给出条目2、3、4和5。
X = train[:,1:] 顺便说一句,您可以通过在每一行前包括四个空格(只需高亮显示并点击Ctrl+K)来使代码格式正确。
发布于 2017-07-07 07:46:43
对于单维度切片,即使在普通列表中,您也应该知道如下所示:
[start : end]使用start included和end excluded。
您还可以使用以下这些:
[:x] # from the start to x
[x:] # from x to the end然后,您可以将其概括为2D或更多,因此在您的情况下是:
X = train[:,1:] # the first : to get all rows, and 1: to get all columns except the first如果您愿意,可以在这里中了解更多有关这些信息,这是一个很好的实践方法
https://stackoverflow.com/questions/44965192
复制相似问题