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

落爺英雄遲暮 提交于 2020-12-27 08:10:45

问题


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

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]

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

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




回答2:


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]




回答3:


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.

The syntax is 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



来源:https://stackoverflow.com/questions/33491703/meaning-of-x-x-1-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!