【问题标题】:Python - numpy array syntax confusion?Python - numpy 数组语法混乱?
【发布时间】:2018-02-06 19:41:29
【问题描述】:

我正在关注我正在阅读的书中的这个 SVM 分类器示例代码。

我是 Python 新手,很难理解/可视化所有这些数组语法 [:,1] [:,:-1]。有人可以解释一下最后三行代码应该是什么意思/做什么。我将不胜感激。

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)

【问题讨论】:

标签: python numpy syntax


【解决方案1】:

Numpy 数组提供的功能远远超出了 Python 列表的能力。

还有,在numpy切片中是表示数组的维度。

考虑一个 3x3 矩阵,它有 2 个维度。让我们看看一些操作在 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]) 的数组。即array([2,4,5])

同样,npa[:,:-1] 将为每一行 ([:,) 提供除最后一列 (,:-1]) 之外的每一列的数组。即array([[1,2],[3,4], [4,5]])

参考在这里:https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

【讨论】:

  • @CristiArde 如果这个答案能够消除你的疑惑,请接受答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
相关资源
最近更新 更多