Python 中 X = X[:, 1] 的含义
Meaning of X = X[:, 1] in Python
我正在研究这段 python 代码。最后一行的 X = X[:, 1]
是什么意思?
def linreg(X,Y):
# Running the linear regression
X = sm.add_constant(X)
model = regression.linear_model.OLS(Y, X).fit()
a = model.params[0]
b = model.params[1]
X = X[:, 1]
x = np.random.rand(3,2)
x
Out[37]:
array([[ 0.03196827, 0.50048646],
[ 0.85928802, 0.50081615],
[ 0.11140678, 0.88828011]])
x = x[:,1]
x
Out[39]: array([ 0.50048646, 0.50081615, 0.88828011])
那一行所做的是 sliced 数组,获取所有行 (:
) 但保留第二列 (1
)
这就像你在指定轴一样简单。考虑起始列为 0,然后当您经过 1,2 等等时。
语法是x[row_index,column_index]
您还可以根据需要在 row_index 中指定行值范围,此外 eg:1:13 提取前 13 行以及列
中指定的内容
你应该知道的事
您需要搜索的词是切片。
x[start:end:step] 是完整形式,
这里我们可以省略使用默认值:开始默认为 0 ,结束默认为列表的长度,步骤默认为 1 。
因此 x[:] 与 x[0:len(x):1]
相同
x[:,1] 这是二维切片,这里是x[row_index, column_index]
我正在研究这段 python 代码。最后一行的 X = X[:, 1]
是什么意思?
def linreg(X,Y):
# Running the linear regression
X = sm.add_constant(X)
model = regression.linear_model.OLS(Y, X).fit()
a = model.params[0]
b = model.params[1]
X = X[:, 1]
x = np.random.rand(3,2)
x
Out[37]:
array([[ 0.03196827, 0.50048646],
[ 0.85928802, 0.50081615],
[ 0.11140678, 0.88828011]])
x = x[:,1]
x
Out[39]: array([ 0.50048646, 0.50081615, 0.88828011])
那一行所做的是 sliced 数组,获取所有行 (:
) 但保留第二列 (1
)
这就像你在指定轴一样简单。考虑起始列为 0,然后当您经过 1,2 等等时。
语法是x[row_index,column_index]
您还可以根据需要在 row_index 中指定行值范围,此外 eg:1:13 提取前 13 行以及列
中指定的内容你应该知道的事
您需要搜索的词是切片。 x[start:end:step] 是完整形式, 这里我们可以省略使用默认值:开始默认为 0 ,结束默认为列表的长度,步骤默认为 1 。 因此 x[:] 与 x[0:len(x):1]
相同x[:,1] 这是二维切片,这里是x[row_index, column_index]