Python: - has built-in
NumPy is:
importnumpyasnp
a=np.array([0,1,2,3])a
array([0, 1, 2, 3])
l=range(1000)%timeit [i**2 for i in l]
319 µs ± 10.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
a=np.arange(1000)%timeit a**2
1.04 µs ± 39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
help(np.array)
Help on built-in function array in module numpy: array(...) array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0) Create an array. Parameters ---------- object : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`dtype`, `order`, etc.). order : {'K', 'A', 'C', 'F'}, optional Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless 'F' is specified, in which case it will be in Fortran order (column major). If object is an array the following holds. ===== ========= =================================================== order no copy copy=True ===== ========= =================================================== 'K' unchanged F & C order preserved, otherwise most similar order 'A' unchanged F order if input is F and not C, otherwise C order 'C' C order C order 'F' F order F order ===== ========= =================================================== When ``copy=False`` and a copy is made for other reasons, the result is the same as if ``copy=True``, with some exceptions for `A`, see the Notes section. The default order is 'K'. subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement. Returns ------- out : ndarray An array object satisfying the specified requirements. See Also -------- empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. ones : Return a new array setting values to one. zeros : Return a new array setting values to zero. full : Return a new array of given shape filled with value. Notes ----- When order is 'A' and `object` is an array in neither 'C' nor 'F' order, and a copy is forced by a change in dtype, then the order of the result is not necessarily 'C' as expected. This is likely a bug. Examples -------- >>> np.array([1, 2, 3]) array([1, 2, 3]) Upcasting: >>> np.array([1, 2, 3.0]) array([ 1., 2., 3.]) More than one dimension: >>> np.array([[1, 2], [3, 4]]) array([[1, 2], [3, 4]]) Minimum dimensions 2: >>> np.array([1, 2, 3], ndmin=2) array([[1, 2, 3]]) Type provided: >>> np.array([1, 2, 3], dtype=complex) array([ 1.+0.j, 2.+0.j, 3.+0.j]) Data-type consisting of more than one element: >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')]) >>> x['a'] array([1, 3]) Creating an array from sub-classes: >>> np.array(np.mat('1 2; 3 4')) array([[1, 2], [3, 4]]) >>> np.array(np.mat('1 2; 3 4'), subok=True) matrix([[1, 2], [3, 4]])
np.lookfor('create array')
Search results for 'create array' --------------------------------- numpy.array Create an array. numpy.memmap Create a memory-map to an array stored in a *binary* file on disk. numpy.diagflat Create a two-dimensional array with the flattened input as a diagonal. numpy.fromiter Create a new 1-dimensional array from an iterable object. numpy.partition Return a partitioned copy of an array. numpy.ctypeslib.as_array Create a numpy array from a ctypes array or POINTER. numpy.ma.diagflat Create a two-dimensional array with the flattened input as a diagonal. numpy.ma.make_mask Create a boolean mask from an array. numpy.lib.Arrayterator Buffered iterator for big arrays. numpy.ctypeslib.as_ctypes Create and return a ctypes object from a numpy array. Actually numpy.ma.mrecords.fromarrays Creates a mrecarray from a (flat) list of masked arrays. numpy.ma.mvoid.__new__ Create a new masked array from scratch. numpy.ma.MaskedArray.__new__ Create a new masked array from scratch. numpy.ma.mrecords.fromtextfile Creates a mrecarray from data stored in the file `filename`. numpy.asarray Convert the input to an array. numpy.ndarray ndarray(shape, dtype=float, buffer=None, offset=0, numpy.recarray Construct an ndarray that allows field access using attributes. numpy.chararray chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, numpy.exp Calculate the exponential of all elements in the input array. numpy.pad Pad an array. numpy.asanyarray Convert the input to an ndarray, but pass ndarray subclasses through. numpy.cbrt Return the cube-root of an array, element-wise. numpy.copy Return an array copy of the given object. numpy.diag Extract a diagonal or construct a diagonal array. numpy.exp2 Calculate `2**p` for all `p` in the input array. numpy.fmax Element-wise maximum of array elements. numpy.fmin Element-wise minimum of array elements. numpy.load Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. numpy.modf Return the fractional and integral parts of an array, element-wise. numpy.rint Round elements of the array to the nearest integer. numpy.sort Return a sorted copy of an array. numpy.sqrt Return the non-negative square-root of an array, element-wise. numpy.array_equiv Returns True if input arrays are shape consistent and all elements equal. numpy.dtype Create a data type object. numpy.expm1 Calculate ``exp(x) - 1`` for all elements in the array. numpy.isnan Test element-wise for NaN and return result as a boolean array. numpy.isnat Test element-wise for NaT (not a time) and return result as a boolean array. numpy.log10 Return the base 10 logarithm of the input array, element-wise. numpy.log1p Return the natural logarithm of one plus the input array, element-wise. numpy.power First array elements raised to powers from second array, element-wise. numpy.ufunc Functions that operate element by element on whole arrays. numpy.choose Construct an array from an index array and a set of arrays to choose from. numpy.nditer Efficient multi-dimensional iterator object to iterate over arrays. numpy.maximum Element-wise maximum of array elements. numpy.minimum Element-wise minimum of array elements. numpy.swapaxes Interchange two axes of an array. numpy.full_like Return a full array with the same shape and type as a given array. numpy.ones_like Return an array of ones with the same shape and type as a given array. numpy.bitwise_or Compute the bit-wise OR of two arrays element-wise. numpy.empty_like Return a new array with the same shape and type as a given array. numpy.zeros_like Return an array of zeros with the same shape and type as a given array. numpy.asarray_chkfinite Convert the input to an array, checking for NaNs or Infs. numpy.bitwise_and Compute the bit-wise AND of two arrays element-wise. numpy.bitwise_xor Compute the bit-wise XOR of two arrays element-wise. numpy.float_power First array elements raised to powers from second array, element-wise. numpy.ma.exp Calculate the exponential of all elements in the input array. numpy.diag_indices Return the indices to access the main diagonal of an array. numpy.nested_iters Create nditers for use in nested loops numpy.ma.sqrt Return the non-negative square-root of an array, element-wise. numpy.ma.log10 Return the base 10 logarithm of the input array, element-wise. numpy.chararray.tolist a.tolist() numpy.put_along_axis Put values into the destination array by matching 1d index and data slices. numpy.ma.choose Use an index array to construct a new array from a set of choices. numpy.ma.maximum Element-wise maximum of array elements. numpy.ma.minimum Element-wise minimum of array elements. numpy.ma.mrecords.MaskedRecords.__new__ Create a new masked array from scratch. numpy.savez_compressed Save several arrays into a single file in compressed ``.npz`` format. numpy.matlib.rand Return a matrix of random values with given shape. numpy.datetime_as_string Convert an array of datetimes into an array of strings. numpy.ma.bitwise_or Compute the bit-wise OR of two arrays element-wise. numpy.ma.bitwise_and Compute the bit-wise AND of two arrays element-wise. numpy.ma.bitwise_xor Compute the bit-wise XOR of two arrays element-wise. numpy.ma.make_mask_none Return a boolean mask of the given shape, filled with False. numpy.core._multiarray_umath.clip Clip (limit) the values in an array. numpy.core.tests.test_overrides._new_duck_type_and_implements Create a duck array type and implements functions. numpy.ma.mrecords.fromrecords Creates a MaskedRecords from a list of records. numpy.core._multiarray_umath.empty_like Return a new array with the same shape and type as a given array. numpy.f2py.tests.test_array_from_pyobj.Array.has_shared_memory Check that created array shares data with input array. numpy.core._dtype._construction_repr Creates a string repr of the dtype, excluding the 'dtype()' part numpy.abs Calculate the absolute value element-wise. numpy.add Add arguments element-wise. numpy.cos Cosine element-wise. numpy.log Natural logarithm, element-wise. numpy.mod Return element-wise remainder of division. numpy.lib.recfunctions.require_fields Casts a structured array to a new dtype using assignment by field-name. numpy.sin Trigonometric sine, element-wise. numpy.tan Compute tangent element-wise. numpy.ceil Return the ceiling of the input, element-wise. numpy.conj Return the complex conjugate, element-wise. numpy.cosh Hyperbolic cosine, element-wise. numpy.fabs Compute the absolute values element-wise. numpy.fmod Return the element-wise remainder of division. numpy.less Return the truth value of (x1 < x2) element-wise. numpy.log2 Base-2 logarithm of `x`. numpy.sign Returns an element-wise indication of the sign of a number. numpy.sinh Hyperbolic sine, element-wise. numpy.tanh Compute hyperbolic tangent element-wise. numpy.equal Return (x1 == x2) element-wise. numpy.core._multiarray_umath.datetime_as_string Convert an array of datetimes into an array of strings. numpy.floor Return the floor of the input, element-wise. numpy.frexp Decompose the elements of x into mantissa and twos exponent. numpy.hypot Given the "legs" of a right triangle, return its hypotenuse. numpy.isinf Test element-wise for positive or negative infinity. numpy.ldexp Returns x1 * 2**x2, element-wise. numpy.trunc Return the truncated value of the input, element-wise. numpy.arccos Trigonometric inverse cosine, element-wise. numpy.arcsin Inverse sine, element-wise. numpy.arctan Trigonometric inverse tangent, element-wise. numpy.around Evenly round to the given number of decimals. numpy.divide Returns a true division of the inputs, element-wise. numpy.divmod Return element-wise quotient and remainder simultaneously. numpy.source Print or write to a file the source code for a NumPy object. numpy.square Return the element-wise square of the input. numpy.arccosh Inverse hyperbolic cosine, element-wise. numpy.arcsinh Inverse hyperbolic sine element-wise. numpy.arctan2 Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly. numpy.arctanh Inverse hyperbolic tangent element-wise. numpy.deg2rad Convert angles from degrees to radians. numpy.degrees Convert angles from radians to degrees. numpy.greater Return the truth value of (x1 > x2) element-wise. numpy.rad2deg Convert angles from radians to degrees. numpy.radians Convert angles from degrees to radians. numpy.signbit Returns element-wise True where signbit is set (less than zero). numpy.spacing Return the distance between x and the nearest adjacent number. numpy.copysign Change the sign of x1 to that of x2, element-wise. numpy.diagonal Return specified diagonals. numpy.isfinite Test element-wise for finiteness (not infinity or not Not a Number). numpy.multiply Multiply arguments element-wise. numpy.negative Numerical negative, element-wise. numpy.subtract Subtract arguments, element-wise. numpy.heaviside Compute the Heaviside step function. numpy.logaddexp Logarithm of the sum of exponentiations of the inputs. numpy.nextafter Return the next floating-point value after x1 towards x2, element-wise. numpy.not_equal Return (x1 != x2) element-wise. numpy.left_shift Shift the bits of an integer to the left. numpy.less_equal Return the truth value of (x1 =< x2) element-wise. numpy.logaddexp2 Logarithm of the sum of exponentiations of the inputs in base-2. numpy.logical_or Compute the truth value of x1 OR x2 element-wise. numpy.nan_to_num Replace NaN with zero and infinity with large finite numbers (default numpy.reciprocal Return the reciprocal of the argument, element-wise. numpy.bitwise_not Compute bit-wise inversion, or bit-wise NOT, element-wise. numpy.einsum_path Evaluates the lowest cost contraction order for an einsum expression by numpy.histogram2d Compute the bi-dimensional histogram of two data samples. numpy.logical_and Compute the truth value of x1 AND x2 element-wise. numpy.logical_not Compute the truth value of NOT x element-wise. numpy.logical_xor Compute the truth value of x1 XOR x2, element-wise. numpy.right_shift Shift the bits of an integer to the right. numpy.ma.abs Calculate the absolute value element-wise. numpy.ma.add Add arguments element-wise. numpy.ma.cos Cosine element-wise. numpy.ma.log Natural logarithm, element-wise. numpy.ma.mod Return element-wise remainder of division. numpy.ma.sin Trigonometric sine, element-wise. numpy.ma.tan Compute tangent element-wise. numpy.floor_divide Return the largest integer smaller or equal to the division of the inputs. numpy.ma.ceil Return the ceiling of the input, element-wise. numpy.ma.cosh Hyperbolic cosine, element-wise. numpy.fft.ifft Compute the one-dimensional inverse discrete Fourier Transform. numpy.ma.fabs Compute the absolute values element-wise. numpy.ma.fmod Return the element-wise remainder of division. numpy.ma.less Return the truth value of (x1 < x2) element-wise. numpy.ma.log2 Base-2 logarithm of `x`. numpy.ma.sinh Hyperbolic sine, element-wise. numpy.ma.tanh Compute hyperbolic tangent element-wise. numpy.greater_equal Return the truth value of (x1 >= x2) element-wise. numpy.fft.ifftn Compute the N-dimensional inverse discrete Fourier Transform. numpy.ma.equal Return (x1 == x2) element-wise. numpy.ma.floor Return the floor of the input, element-wise. numpy.ma.hypot Given the "legs" of a right triangle, return its hypotenuse. numpy.busdaycalendar A business day calendar object that efficiently stores information numpy.ma.arccos Trigonometric inverse cosine, element-wise. numpy.ma.arcsin Inverse sine, element-wise. numpy.ma.arctan Trigonometric inverse tangent, element-wise. numpy.ma.divide Returns a true division of the inputs, element-wise. numpy.lib.recfunctions.unstructured_to_structured Converts and n-D unstructured array into an (n-1)-D structured array. numpy.ma.arccosh Inverse hyperbolic cosine, element-wise. numpy.ma.arcsinh Inverse hyperbolic sine element-wise. numpy.ma.arctan2 Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly. numpy.ma.arctanh Inverse hyperbolic tangent element-wise. numpy.ma.greater Return the truth value of (x1 > x2) element-wise. numpy.ma.multiply Multiply arguments element-wise. numpy.ma.negative Numerical negative, element-wise. numpy.ma.subtract Subtract arguments, element-wise. numpy.ma.conjugate Return the complex conjugate, element-wise. numpy.ma.not_equal Return (x1 != x2) element-wise. numpy.ma.remainder Return element-wise remainder of division. numpy.ma.empty_like empty_like(prototype, dtype=None, order='K', subok=True, shape=None) numpy.ma.less_equal Return the truth value of (x1 =< x2) element-wise. numpy.ma.logical_or Compute the truth value of x1 OR x2 element-wise. numpy.ma.logical_and Compute the truth value of x1 AND x2 element-wise. numpy.ma.logical_not Compute the truth value of NOT x element-wise. numpy.ma.logical_xor Compute the truth value of x1 XOR x2, element-wise. numpy.ma.true_divide Returns a true division of the inputs, element-wise. numpy.ma.floor_divide Return the largest integer smaller or equal to the division of the inputs. numpy.ma.greater_equal Return the truth value of (x1 >= x2) element-wise. numpy.core.tests.test_function_base.PhysicalQuantity2 ndarray(shape, dtype=float, buffer=None, offset=0, numpy.lib.tests.test_stride_tricks.SimpleSubClass ndarray(shape, dtype=float, buffer=None, offset=0, numpy.core.tests.test_numeric.TestKeepdims.sub_array ndarray(shape, dtype=float, buffer=None, offset=0, numpy.lib.tests.test_stride_tricks.VerySimpleSubClass ndarray(shape, dtype=float, buffer=None, offset=0, numpy.core.tests.test_multiarray.TestArrayPriority.Foo ndarray(shape, dtype=float, buffer=None, offset=0, numpy.core.tests.test_multiarray.TestArrayPriority.Bar ndarray(shape, dtype=float, buffer=None, offset=0, numpy.testing._gen_alignment_data generator producing data with different alignment and offsets numpy.random.RandomState.rand Random values in a given shape.
help(np.lookfor)
Help on function lookfor in module numpy: lookfor(what, module=None, import_modules=True, regenerate=False, output=None) Do a keyword search on docstrings. A list of objects that matched the search is displayed, sorted by relevance. All given keywords need to be found in the docstring for it to be returned as a result, but the order does not matter. Parameters ---------- what : str String containing words to look for. module : str or list, optional Name of module(s) whose docstrings to go through. import_modules : bool, optional Whether to import sub-modules in packages. Default is True. regenerate : bool, optional Whether to re-generate the docstring cache. Default is False. output : file-like, optional File-like object to write the output to. If omitted, use a pager. See Also -------- source, info Notes ----- Relevance is determined only roughly, by checking if the keywords occur in the function name, at the start of a docstring, etc. Examples -------- >>> np.lookfor('binary representation') # doctest: +SKIP Search results for 'binary representation' ------------------------------------------ numpy.binary_repr Return the binary representation of the input number as a string. numpy.core.setup_common.long_double_representation Given a binary dump as given by GNU od -b, look for long double numpy.base_repr Return a string representation of a number in the given base system. ...
a=np.array([0,1,2,3])a
array([0, 1, 2, 3])
a.ndim
1
a.shape
(4,)
len(a)
4
b=np.array([[0,1,2],[3,4,5]])b
array([[0, 1, 2], [3, 4, 5]])
b.ndim
2
b.shape
(2, 3)
len(b)
2
c=np.array([[[1],[2]],[[3],[4]]])c
array([[[1], [2]], [[3], [4]]])
c.shape
(2, 2, 1)
print("Number of dimensions in array c: ",c.ndim)
Number of dimensions in array c: 3
#Evenly spaced - notice how it always starts with 0 .. (n-1) and not 1!a=np.arange(10)a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# number of pointsc=np.linspace(0,1,9)# start, end, number of pointsc
array([0. , 0.125, 0.25 , 0.375, 0.5 , 0.625, 0.75 , 0.875, 1. ])
d=np.linspace(0,1,5,endpoint=False)# meaning it doesn't stop at 1.d
array([0. , 0.2, 0.4, 0.6, 0.8])
a=np.ones((3,3))# (3, 3) would be a tuple herea
array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]])
type(a)
numpy.ndarray
b=np.zeros((2,2))b
array([[0., 0.], [0., 0.]])
c=np.eye(3)# An identity matrixc
array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
d=np.diag(np.array([1,2,3,4]))d
array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]])
e=np.random.rand(4)# uniform in [0, 1]e
array([0.50755507, 0.0211933 , 0.43352176, 0.44631306])
f=np.random.randn(4)#Gaussianf# type help(np.random.randn) to understand more
array([ 0.65034618, -0.51433646, 0.53942869, 1.52676162])
np.random.seed(1234)#setting the random seedhelp(np.random.seed)
Help on built-in function seed: seed(...) method of numpy.random.mtrand.RandomState instance seed(self, seed=None) Reseed a legacy MT19937 BitGenerator Notes ----- This is a convenience, legacy function. The best practice is to **not** reseed a BitGenerator, rather to recreate a new one. This method is here for legacy reasons. This example demonstrates best practice. >>> from numpy.random import MT19937 >>> from numpy.random import RandomState, SeedSequence >>> rs = RandomState(MT19937(SeedSequence(123456789))) # Later, you want to restart the stream >>> rs = RandomState(MT19937(SeedSequence(987654321)))
Create an array that looks like this:
$$x = \begin{bmatrix} 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 8 \\ 1 & 6 & 1 & 1 \\ \end{bmatrix}\tag{1}$$and,
another one that looks like this:
$$y = \begin{bmatrix} 0. & 0. & 0. & 0. & 0.\\ 7. & 0. & 0. & 0. & 0.\\ 0. & 8. & 0. & 0. & 0.\\ 0. & 0. & 9. & 0. & 0.\\ 0. & 0. & 0. & 10. & 0.\\ 0. & 0. & 0. & 0. & 11.\\ \end{bmatrix}\tag{2}$$and lastly,
create this simple array
$$\begin{bmatrix} 0. & 0. & 0. & 0. & 0.\\ 0. & 0. & 0. & 0. & 0.\\ 1. & 0. & 0. & 0. & 0.\\ 0. & 1. & 0. & 0. & 0.\\ 0. & 0. & 1. & 0. & 0.\\ 0. & 0. & 0. & 1. & 0.\\ \end{bmatrix}\tag{3}$$help(np.eye)help(np.diag)
Help on function eye in module numpy: eye(N, M=None, k=0, dtype=<class 'float'>, order='C') Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : data-type, optional Data-type of the returned array. order : {'C', 'F'}, optional Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory. .. versionadded:: 1.14.0 Returns ------- I : ndarray of shape (N,M) An array where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- identity : (almost) equivalent function diag : diagonal 2-D array from a 1-D array specified by the user. Examples -------- >>> np.eye(2, dtype=int) array([[1, 0], [0, 1]]) >>> np.eye(3, k=1) array([[0., 1., 0.], [0., 0., 1.], [0., 0., 0.]]) Help on function diag in module numpy: diag(v, k=0) Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using. Parameters ---------- v : array_like If `v` is a 2-D array, return a copy of its `k`-th diagonal. If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th diagonal. k : int, optional Diagonal in question. The default is 0. Use `k>0` for diagonals above the main diagonal, and `k<0` for diagonals below the main diagonal. Returns ------- out : ndarray The extracted diagonal or constructed diagonal array. See Also -------- diagonal : Return specified diagonals. diagflat : Create a 2-D array with the flattened input as a diagonal. trace : Sum along diagonals. triu : Upper triangle of an array. tril : Lower triangle of an array. Examples -------- >>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.diag(x) array([0, 4, 8]) >>> np.diag(x, k=1) array([1, 5]) >>> np.diag(x, k=-1) array([3, 7]) >>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]])
a=np.array([1,2,3])a.dtype
dtype('int64')
b=np.array([1.,2.,3.])b.dtype
dtype('float64')
Remember, different datatypes allow us to store data more compactly but most of the time folks as well as the interpreter auto-detects the datatype from input.
# Make it explicitc=np.array([1,2,3],dtype=float)c.dtype
dtype('float64')
# Default data type is automatically floata=np.ones((3,3))a.dtype
dtype('float64')
# Complexd=np.array([1+2j,4+5j,6+8*1j])d.dtype
dtype('complex128')
# Boole=np.array([True,False,False,True])e.dtype
dtype('bool')
f=np.array(['Bonjour','Hi','Hola','Ole','Namaste Ji'])f.dtype# outputs string containing max 10 letters...
dtype('<U10')
importmatplotlib.pyplotasplt%matplotlib inline
x=np.linspace(0,3,20)y=np.linspace(0,9,20)plt.plot(x,y)# plots a line
[<matplotlib.lines.Line2D at 0x7f8978bdd0d0>]
plt.plot(x,y,'o')
[<matplotlib.lines.Line2D at 0x7f8970c5d6d0>]
image=np.random.rand(40,40)plt.imshow(image,cmap=plt.cm.Blues)plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x7f8970d49af0>
# or...plt.imshow(image,cmap=plt.cm.hot)
<matplotlib.image.AxesImage at 0x7f8978cd4c70>
a=np.arange(10)a# indexing begins at 0 , unlike fortran or
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# For multi-dimensional arrays, indexing are tuples of integersa=np.diag(np.arange(3))a
array([[0, 0, 0], [0, 1, 0], [0, 0, 2]])
a[1,1]
1
a[1]
array([0, 1, 0])
a[2,1]=10# replaces row 3, second value
a
array([[ 0, 0, 0], [ 0, 1, 0], [ 0, 10, 2]])
# Slicinga=np.arange(10)a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[2:9:3]# [start:end:step]
array([2, 5, 8])
a[:4]# note: last index isn't included
array([0, 1, 2, 3])
# all three slice components are not required
a=np.arange(6)+np.arange(0,51,10)[:,np.newaxis]print("Answer to above questions is: ")a
Answer to above questions is:
array([[ 0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15], [20, 21, 22, 23, 24, 25], [30, 31, 32, 33, 34, 35], [40, 41, 42, 43, 44, 45], [50, 51, 52, 53, 54, 55]])
print("Orange is: ",a[0,3:5])# Try similarly others to get more answers and play with this array a bit more
Orange is: [3 4]
np.diag(np.tile(4,4))
array([[4, 0, 0, 0], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]])
x=np.array([0,1,2])np.tile(x,4)
array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2])
y=np.array([[1,2],[3,4]])np.tile(y,3)
array([[1, 2, 1, 2, 1, 2], [3, 4, 3, 4, 3, 4]])
A slicing operation creates a view on the original array, which is just a way of accessing array data. Thus the original array is not copied in memory. You can use np.may_share_memory()
to check if two arrays share the same memory block. Note however, that this uses heuristics and may give you false positives.
a=np.arange(10)a# you get the range from 0 to 9 - total of 10
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
b=a[::2]b# you get every 3rd object, as 0,1 -->2, 2,2 -->4 and so on
array([0, 2, 4, 6, 8])
np.may_share_memory(a,b)
True
b[0]=12#we replace 0 with 12b
array([12, 2, 4, 6, 8])
# So what is a then?a
array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Let's rearrangea=np.arange(10)c=a[::2].copy()# we force copyc[0]=12a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Let's do it step by step
a=np.arange(10)a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
c=a[::2].copy()c
array([0, 2, 4, 6, 8])
c[0]=12c
array([12, 2, 4, 6, 8])
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.may_share_memory(a,c)
False
NumPy arrays can be indexed with slices, but also with boolean or integer arrays (masks). This method is called fancy indexing. It creates copies not views.
np.random.seed(3)a=np.random.randint(0,20,15)a
array([10, 3, 8, 0, 19, 10, 11, 9, 10, 6, 0, 12, 7, 14, 17])
(a%3==0)
array([False, True, False, True, False, False, False, True, False, True, True, True, False, False, False])
mask=(a%3==0)get_from_a=a[mask]get_from_a# you extract a sub-array from mask
array([ 3, 0, 9, 6, 0, 12])
# Indexing with mask can be fun to assign a new value to a sub-arraya[a%3==0]=-1a
array([10, -1, 8, -1, 19, 10, 11, -1, 10, -1, -1, -1, 7, 14, 17])
a=np.arange(10)idx=np.array([[3,4],[6,7]])
idx.shape
(2, 2)
a[idx]
array([[3, 4], [6, 7]])
help(np.diag)
Help on function diag in module numpy: diag(v, k=0) Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using. Parameters ---------- v : array_like If `v` is a 2-D array, return a copy of its `k`-th diagonal. If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th diagonal. k : int, optional Diagonal in question. The default is 0. Use `k>0` for diagonals above the main diagonal, and `k<0` for diagonals below the main diagonal. Returns ------- out : ndarray The extracted diagonal or constructed diagonal array. See Also -------- diagonal : Return specified diagonals. diagflat : Create a 2-D array with the flattened input as a diagonal. trace : Sum along diagonals. triu : Upper triangle of an array. tril : Lower triangle of an array. Examples -------- >>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.diag(x) array([0, 4, 8]) >>> np.diag(x, k=1) array([1, 5]) >>> np.diag(x, k=-1) array([3, 7]) >>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]])
a=np.ones((4,4),dtype=int)a[3,1]=6a[2,3]=8#a[[3, 1], [2, 3]] = [6, 8] - - yoc can also do them togetherprint(a)
[[1 1 1 1] [1 1 1 1] [1 1 1 8] [1 6 1 1]]
b=np.zeros((6,5))b[1:]=np.diag(np.arange(7,12))b
array([[ 0., 0., 0., 0., 0.], [ 7., 0., 0., 0., 0.], [ 0., 8., 0., 0., 0.], [ 0., 0., 9., 0., 0.], [ 0., 0., 0., 10., 0.], [ 0., 0., 0., 0., 11.]])
y=np.eye(6,5,k=-2,dtype=float)y
array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.]])