Python-numpy数组语法混乱?

Python-numpy数组语法混乱?,python,numpy,syntax,Python,Numpy,Syntax,我正在阅读一本书中的SVM分类器示例代码 我是Python新手,很难理解/可视化所有这些数组语法[:,1][:,:-1]。有人能解释一下最后3行代码的意思/作用吗。我将不胜感激 Convert string data to numerical data label_encoder = [] X_encoded = np.empty(X.shape) for i,item in enumerate(X[0]): if item.isdigit(): X_encoded[:,

我正在阅读一本书中的SVM分类器示例代码

我是Python新手,很难理解/可视化所有这些数组语法[:,1][:,:-1]。有人能解释一下最后3行代码的意思/作用吗。我将不胜感激

Convert string data to numerical data
label_encoder = []
X_encoded = np.empty(X.shape)
for i,item in enumerate(X[0]):
    if item.isdigit():
       X_encoded[:, i] = X[:, i]
    else:
      label_encoder.append(preprocessing.LabelEncoder())
      X_encoded[:, i] = label_encoder[-1].fit_transform(X[:, i])

 X = X_encoded[:, :-1].astype(int)
 y = X_encoded[:, -1].astype(int)

Numpy阵列允许的功能远远超出python列表的功能

此外,在numpy中,切片是表示数组的维度

考虑一个3x3矩阵,它有两个维度。让我们看看python列表和numpy数组中的一些操作感觉如何

>>> import numpy as np
>>> py = [[1,2,3],[3,4,5],[4,5,6]]
>>> npa = np.array(py)
>> py[1:3] # [[3, 4, 5], [4, 5, 6]]
>> npa[1:3] # array([[3, 4, 5], [4, 5, 6]])
>>> # get column 2 and 3 from rows 2 and 3 
>>> npa[1:3, 1:3] # row, col
假设您不熟悉列表索引/切片

py[:] # means every element in the array, also is a shorthand to create a copy
向前看,npa[:,1]将为您提供一个包含每行[:,第二列,1]的数组。ie阵列[2,4,5]

类似地,npa[:,:-1]将为每一行[:,]提供一个包含除最后一列以外的每一列的数组,即数组[[1,2],[3,4],[4,5]]


参考资料如下:

什么是phyton?@CristiArde;你可以阅读这篇文章:可能是重复的我看了这些,我理解了,但在这个例子中[:,:-1]我不确定thx是什么意思suggestion@CristiArde如果此答案能够消除您的疑虑,请接受以下答案: