Reputation: 1227
I am studying this snippet of python code. What does X = X[:, 1]
mean in the 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]
Upvotes: 51
Views: 168734
Reputation: 63
It is 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 your need in row_index
, eg:1:13
extracts first 13 rows along with whatever specified in the column
Upvotes: 4
Reputation: 141
The term you need to search for is "slice".
x[start:end:step]
is the full form.
Here we can omit some values and it will use a default value:
0
,1
.And hence x[:]
means the same as x[0:len(x):1]
Upvotes: 14
Reputation: 211
Meaning of X = X[:, 1] in Python is:
for example:
x = array([[0.69859393, 0.1042432 ],
[0.55138493, 0.18639614],
[0.27338772, 0.80351282]])
x[:,1] = array([0.1042432 , 0.18639614, 0.80351282])
Upvotes: 9
Reputation: 211
x[:,1] this is 2d slicing, here x[row_index, column_index]
Upvotes: 3
Reputation: 15953
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
)
Upvotes: 78