Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] 
like image 618
Taewan Avatar asked Nov 03 '15 05:11

Taewan


People also ask

What does it mean in Python list [: 1?

In Python, [::-1] means reversing a string, list, or any iterable with an ordering. For example: hello = "Hello world"

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

What does array 1 :] do in Python?

Simply A[1:] means access elements from 1st position (don't consider A[0]).

What does it mean [: 0 in Python?

[ : , 0 ] means (more or less) [ first_row:last_row , column_0 ] . If you have a 2-dimensional list/matrix/array, this notation will give you all the values in column 0 (from all rows). Follow this answer to receive notifications. edited Jun 11, 2019 at 0:40. NellieK.


1 Answers

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)

like image 63
Leb Avatar answered Sep 22 '22 17:09

Leb