Python 中 X = X[:, 1] 的含义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33491703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:26:45  来源:igfitidea点击:

Meaning of X = X[:, 1] in Python

pythonstatistics

提问by Taewan

I am studying this snippet of python code. What does X = X[:, 1]mean in last line?

我正在研究这段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]

采纳答案by Leb

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])

So what that line did is slicedthe array, taking all rows (:) but keeping the second column (1)

那么该行所做的是对数组进行切片,取所有行 ( :) 但保留第二列 ( 1)

回答by S L SREEJITH

it is simply like you are specifying the axis. Consider the starting column as 0 then as you go through 1,2 and so on.

就像您指定轴一样。将起始列视为 0,然后在您通过 1,2 等时。

The syntax is x[row_index,column_index]

语法是 x[row_index,column_index]

you can also specify a range of row values as per need in row_index also eg:1:13 extracts first 13 rows along with whatever specified in column

您还可以根据需要在 row_index 中指定一系列行值,例如:1:13 提取前 13 行以及列中指定的任何内容

回答by Adiraamruta

Something you shoud know

你应该知道的事

The term you need to search for is slice. x[start:end:step]is the full form, Here we can omit to use a default value: start defaults to 0 , end defaults to the length of the list, and step defaults to 1. And hence x[:] means same as x[0:len(x):1]

您需要搜索的术语是切片。 x[start:end:step]是完整形式,这里我们可以省略使用默认值:start 默认为 0 ,end 默认为列表的长度,step 默认为 1。因此 x[:] 表示与 x[0:len(x):1] 相同