NumPy: creating a two-dimensional array
I just started learning NumPy
. I want to clarify:
b = np.array([[1.5, 2, 3], [4, 5, 6]])
This is creating a two-dimensional array, where b[0][0] = 1.5, b[1][0] = 4, etc.?
2 answers
That's right, you want to throw off what to see for studying ML?
All elements of the matrix b
will have the data type float
(most likely float64
), since one element is 1.5
of the type float
.
float
- a more "strong" type compared to int
, i.e. a value of type int
(meaning Numpy data types, not Python int
with unlimited precision) can be converted to float
without loss of precision (information), and not back:
In [56]: b
Out[56]:
array([[1.5, 2. , 3. ],
[4. , 5. , 6. ]])
In [57]: b.dtype
Out[57]: dtype('float64')
Indexing in Numpy is much more "advanced" compared to standard Python indexing. lists:
In [58]: b[1,0]
Out[58]: 4.0
Here, before the comma, it is the index (s) of the elements in the first dimension / axis (rows in the case of 2D array
), after the comma in the second dimension (columns for a 2D array).
Here are more interesting cases:
In [67]: a = np.arange(12).reshape(4,3)
In [68]: a
Out[68]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [69]: a[:, 1]
Out[69]: array([ 1, 4, 7, 10])
In [70]: a[:, 2]
Out[70]: array([ 2, 5, 8, 11])
In [71]: a[2, :]
Out[71]: array([6, 7, 8])
In [72]: a[[1,2], :]
Out[72]:
array([[3, 4, 5],
[6, 7, 8]])