In [1]:
import numpy as np
Create a new array of 2*2 integers, without initializing entries.
In [2]:
np.array([[1, 2],[3, 4]])
Out[2]:
Let X = np.array([1,2,3], [4,5,6], np.int32). Create a new array with the same shape and type as X.
In [10]:
X = np.array([[1,2,3], [4,5,6]], np.int32)
X
Out[10]:
Create a 3-D array with ones on the diagonal and zeros elsewhere.
In [4]:
np.identity(3)
Out[4]:
In [5]:
np.eye(3)
Out[5]:
Create a new array of 3*2 float numbers, filled with ones.
In [7]:
np.ones((3,2))
Out[7]:
Let x = np.arange(4, dtype=np.int64). Create an array of ones with the same shape and type as X.
In [12]:
x = np.reshape(np.arange(4, dtype=np.int64), (2, 2))
x
Out[12]:
Create a new array of 3*2 float numbers, filled with zeros.
In [9]:
np.ones((3, 2))
Out[9]:
Let x = np.arange(4, dtype=np.int64). Create an array of zeros with the same shape and type as X.
In [14]:
x = np.reshape(np.arange(4, dtype=np.int64), (2,2))
x
Out[14]:
Create a new array of 2*5 uints, filled with 6.
In [15]:
x = np.full((2, 4), 6)
print(x)
Let x = np.arange(4, dtype=np.int64). Create an array of 6's with the same shape and type as X.
In [16]:
x = np.arange(4, dtype=np.int64)
print(x)
x.fill(6)
print(x)
Create an array of [1, 2, 3].
In [17]:
np.array([1, 2, 3])
Out[17]:
Let x = [1, 2]. Convert it into an array.
In [18]:
x = [1,2]
np.asarray(x)
Out[18]:
Let X = np.array([[1, 2], [3, 4]]). Convert it into a matrix.
In [20]:
X = np.array([[1, 2], [3, 4]])
np.asmatrix(X)
Out[20]:
Let x = [1, 2]. Conver it into an array of float.
In [21]:
x = [1, 2]
np.asarray(x, dtype=np.float)
Out[21]:
Let x = np.array([30]). Convert it into scalar of its single element, i.e. 30.
In [22]:
x = np.array([30])
np.asscalar(x)
Out[22]:
Let x = np.array([1, 2, 3]). Create a array copy of x, which has a different id from x.
In [24]:
x = np.array([1, 2, 3])
x2 = x.copy()
print(id(x), id(x2))
Create an array of 2, 4, 6, 8, ..., 100.
In [32]:
np.array(range(2, 101, 2))
np.arange(2, 101, 2)
Out[32]:
Create a 1-D array of 50 evenly spaced elements between 3. and 10., inclusive.
In [35]:
np.linspace(3, 10, 50)
Out[35]:
Create a 1-D array of 50 element spaced evenly on a log scale between 3. and 10., exclusive.
In [36]:
np.logspace(3, 10, 50)
Out[36]:
Let X = np.array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]). Get the diagonal of X, that is, [0, 5, 10].
In [39]:
X = np.array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
# np.reshape(X, (3, 4))
np.diag(X)
Out[39]:
Create a 2-D array whose diagonal equals [1, 2, 3, 4] and 0's elsewhere.
In [40]:
np.diagflat([1, 2, 3, 4])
Out[40]:
Create an array which looks like below. array([[ 0., 0., 0., 0., 0.], [ 1., 0., 0., 0., 0.], [ 1., 1., 0., 0., 0.]])
In [42]:
np.tri(3, 5, -1)
Out[42]:
Create an array which looks like below. array([[ 0, 0, 0], [ 4, 0, 0], [ 7, 8, 0], [10, 11, 12]])
In [101]:
Out[101]:
Create an array which looks like below. array([[ 1, 2, 3], [ 4, 5, 6], [ 0, 8, 9], [ 0, 0, 12]])
In [102]:
Out[102]: