Prev: What is 'numpy'? | Next: Array construction (cont'd)
...always use:
import numpy as np
This will allow you to clearly distinguish the imported namespace using the 'np.' prefix
import numpy as np
# Pass a list argument to array() method
alist = [1,2,3,4,5]
ar = np.array(alist)
print(ar,'\n')
# or directly
ar = np.array([1,2,3,4,5])
print(ar,'\n')
# Be careful for this frequent error
#ar = np.array(1,2,3,4,5) # WRONG: argument should be a list; brackets should be included
# You may explicitely define the type of the array elements
b = np.array([1.2, 3.5, 5.1], dtype='float')
print(b,'\n')
c = np.array([1,2,3,4,5], 'int')
print(c,'\n')
d = np.array([1,2,3,4,5])
print(d,'\n',type(d))
import numpy as np
alist = [i for i in range(10000)]
ar = np.array(alist)
print('list performance using comprehension:')
%timeit [i**2 for i in alist]
print('\nndarray performance using comprehension:')
%timeit [i**2 for i in ar]
print('\nndarray performance using vectorized pow():')
%timeit pow(ar,2)
import numpy as np
ar = np.array([1,2,3,4,5])
print(ar.ndim)
import numpy as np
# 2D arrays
# Note the external brackets enclosing the two lists
br = np.array([[1,2,3,4],[5,6,7,8]])
print(br,'\n', br.ndim,'\n')
cr = np.array([[1,2,3],[5,6,7],[8,9,10]])
print(cr,'\n', cr.ndim,'\n')
import numpy as np
# 3D arrays
# Note the external brackets enclosing the two lists of lists (2D arrays)
ar3 = np.array([[[1,2,3,4],[5,6,7,8]], [[10,20,30,40],[50,60,70,80]]])
print(ar3,'\n', ar3.ndim,'\n')
import numpy as np
ar = np.array([np.random.randint(1,101) for i in range(10)])
print(ar)
print(ar.ndim)
- See that we have called the numpy random.randint() function (not the Python random.randint), which is part of numpy.random module; you can read more about this module here
- Get used to reading the numpy documentation: it is of key importance in learning how to make the most out of it.
import numpy as np
ar = np.array([[np.random.randint(1,101) for i in range(5)],
[np.random.randint(1,101) for i in range(5)]])
print(ar)
print(ar.ndim)
. Free learning material
. See full copyright and disclaimer notice