0% found this document useful (0 votes)
1 views

Lab 3

The document provides an overview of basic operations and functionalities of NumPy arrays, including creation, manipulation, and mathematical operations. It covers one-dimensional and two-dimensional arrays, array attributes like shape and dtype, and various methods for array creation such as zeros, arange, and linspace. Additionally, it demonstrates array indexing, reshaping, and performing mathematical operations like addition and multiplication.

Uploaded by

mohdrahib.2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Lab 3

The document provides an overview of basic operations and functionalities of NumPy arrays, including creation, manipulation, and mathematical operations. It covers one-dimensional and two-dimensional arrays, array attributes like shape and dtype, and various methods for array creation such as zeros, arange, and linspace. Additionally, it demonstrates array indexing, reshaping, and performing mathematical operations like addition and multiplication.

Uploaded by

mohdrahib.2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

array basics

In [1]: import numpy as np

In [2]: myarr=np.array([1,4,65521234345,8,4], np.int64) # 1 D

In [3]: myarr

Out[3]: array([ 1, 4, 65521234345, 8, 4],


dtype=int64)

In [4]: myarr[2]

Out[4]: 65521234345

In [5]: #myarr[0,1]

In [6]: myarr=np.array([[1,4,65521234345,8,4]], np.int64) # 2 D

In [7]: #myarr[2]

In [8]: myarr[0,2]

Out[8]: 65521234345

In [9]: myarr.shape

Out[9]: (1, 5)

In [10]: myarr.dtype

Out[10]: dtype('int64')

In [11]: myarr[0,2]=90

In [12]: myarr

Out[12]: array([[ 1, 4, 90, 8, 4]], dtype=int64)

array creation: conversion from other


python structures
In [13]: listarr=np.array([[1,2,3],[4,5,6],[7,8,9]])

In [14]: listarr

Out[14]: array([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]])

In [15]: listarr.shape
Out[15]: (3, 3)

In [16]: listarr.dtype

Out[16]: dtype('int32')

In [17]: listarr.size

Out[17]: 9

In [18]: listarr[2,2]=78
listarr

Out[18]: array([[ 1, 2, 3],


[ 4, 5, 6],
[ 7, 8, 78]])

In [19]: np.array({43,56,56,43}) #using sets..it's dtype is object

Out[19]: array({56, 43}, dtype=object)

In [20]: zeros1=np.zeros(4)
zeros=np.zeros((2,6,4))

In [21]: zeros

Out[21]: array([[[0., 0., 0., 0.],


[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],

[[0., 0., 0., 0.],


[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]])

In [22]: zeros1

Out[22]: array([0., 0., 0., 0.])

In [23]: zeros.shape

Out[23]: (2, 6, 4)

In [24]: zeros.dtype

Out[24]: dtype('float64')

In [25]: zeros.size

Out[25]: 48

In [26]: zeros1
Out[26]: array([0., 0., 0., 0.])

In [27]: np.arange(4)

Out[27]: array([0, 1, 2, 3])

In [28]: lspace= np.linspace(0,40,5)

In [29]: lspace

Out[29]: array([ 0., 10., 20., 30., 40.])

In [30]: emp=np.empty(2)

In [31]: emp

Out[31]: array([1.51756124e-182, 2.15011297e-057])

In [32]: emp_like=np.empty_like(zeros)

In [33]: #emp_like

print(emp_like)
print(emp_like.shape)
print(emp_like.size)
print(emp_like.dtype)

[[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]]
(2, 6, 4)
48
float64

In [34]: ide=np.identity(10)

In [35]: ide
Out[35]: array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])

In [36]: ide.shape

Out[36]: (10, 10)

In [37]: ide.size

Out[37]: 100

In [38]: ide.dtype

Out[38]: dtype('float64')

In [39]: arr=np.arange(90)

In [40]: arr

Out[40]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1


6,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 3
3,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5
0,
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 6
7,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 8
4,
85, 86, 87, 88, 89])

In [41]: arr=arr.reshape(5,18)

In [42]: arr

Out[42]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,


16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
88, 89]])

In [43]: arr.shape

Out[43]: (5, 18)


In [44]: arr.dtype

Out[44]: dtype('int32')

In [45]: arr=arr.ravel()

In [46]: arr

Out[46]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1


6,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 3
3,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5
0,
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 6
7,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 8
4,
85, 86, 87, 88, 89])

In [47]: arr.shape

Out[47]: (90,)

In [48]: x=[[1,2,3],[4,5,6],[7,8,9]]

In [49]: ar=np.array(x)

In [50]: ar

Out[50]: array([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]])

In [51]: ar.sum(axis=0)

Out[51]: array([12, 15, 18])

In [52]: ar.sum(axis=1)

Out[52]: array([ 6, 15, 24])

In [53]: ar.T

Out[53]: array([[1, 4, 7],


[2, 5, 8],
[3, 6, 9]])

In [54]: ar.flat

Out[54]: <numpy.flatiter at 0x23dc399caf0>

In [55]: for i in ar.flat:


print(i)
1
2
3
4
5
6
7
8
9

In [56]: ar.ndim

Out[56]: 2

In [57]: ar.size

Out[57]: 9

In [58]: ar.itemsize

Out[58]: 4

In [59]: ar.dtype

Out[59]: dtype('int32')

In [60]: ar.nbytes

Out[60]: 36

In [61]: print(ar.sum())
print(ar.max())
print(ar.min())

45
9
1

In [62]: ar.argmax()

Out[62]: 8

In [63]: ar.argmin()

Out[63]: 0

In [64]: ar.argsort()

Out[64]: array([[0, 1, 2],


[0, 1, 2],
[0, 1, 2]], dtype=int64)

In [65]: ar.argmax(axis=0)

Out[65]: array([2, 2, 2], dtype=int64)

In [66]: ar.argmax(axis=1)
Out[66]: array([2, 2, 2], dtype=int64)

In [67]: ar.argmin(axis=0)

Out[67]: array([0, 0, 0], dtype=int64)

In [68]: ar.argmin(axis=1)

Out[68]: array([0, 0, 0], dtype=int64)

In [69]: k=np.array([1,3,4,675,2])
k

Out[69]: array([ 1, 3, 4, 675, 2])

In [70]: k.argsort()

Out[70]: array([0, 4, 1, 2, 3], dtype=int64)

In [71]: y=[[1,2,3],[4,15,6],[17,8,9]]
z=np.array(y)
print(z)
z.argsort(axis=1)

[[ 1 2 3]
[ 4 15 6]
[17 8 9]]
Out[71]: array([[0, 1, 2],
[0, 2, 1],
[1, 2, 0]], dtype=int64)

mathematical operations in array: matrix addition multiplication etc

In [72]: ar1=np.array([[1,2,1],[4,0,6],[8,1,0]])

In [73]: ar1

Out[73]: array([[1, 2, 1],


[4, 0, 6],
[8, 1, 0]])

In [74]: ar2=np.array([[1,2,3],[4,5,6],[7,1,0]])

In [75]: ar2

Out[75]: array([[1, 2, 3],


[4, 5, 6],
[7, 1, 0]])

In [76]: ar1+ar2

Out[76]: array([[ 2, 4, 4],


[ 8, 5, 12],
[15, 2, 0]])

In [77]: multi= ar1 * ar2


multi
Out[77]: array([[ 1, 4, 3],
[16, 0, 36],
[56, 1, 0]])

In [78]: np.sqrt(multi)

Out[78]: array([[1. , 2. , 1.73205081],


[4. , 0. , 6. ],
[7.48331477, 1. , 0. ]])

In [79]: np.where(ar2>5)

Out[79]: (array([1, 2], dtype=int64), array([2, 0], dtype=int64))

In [80]: np.count_nonzero(ar1)

Out[80]: 7

In [81]: np.nonzero(ar1)

Out[81]: (array([0, 0, 0, 1, 1, 2, 2], dtype=int64),


array([0, 1, 2, 0, 2, 0, 1], dtype=int64))

In [82]: ar1[1,2]=0

In [83]: np.count_nonzero(ar1)

Out[83]: 6

In [84]: py_ar=[0,4,55,2]

In [85]: np_ar=np.array(py_ar)

In [86]: import sys

In [87]: sys.getsizeof(1)

Out[87]: 28

In [88]: sys.getsizeof(1) * len(py_ar)

Out[88]: 112

In [89]: np_ar.size

Out[89]: 4

In [90]: np_ar.itemsize

Out[90]: 4

In [91]: np_ar.itemsize * np_ar.size

Out[91]: 16

In [92]: dir(np)
Out[92]: ['ALLOW_THREADS',
'AxisError',
'BUFSIZE',
'CLIP',
'ComplexWarning',
'DataSource',
'ERR_CALL',
'ERR_DEFAULT',
'ERR_IGNORE',
'ERR_LOG',
'ERR_PRINT',
'ERR_RAISE',
'ERR_WARN',
'FLOATING_POINT_SUPPORT',
'FPE_DIVIDEBYZERO',
'FPE_INVALID',
'FPE_OVERFLOW',
'FPE_UNDERFLOW',
'False_',
'Inf',
'Infinity',
'MAXDIMS',
'MAY_SHARE_BOUNDS',
'MAY_SHARE_EXACT',
'ModuleDeprecationWarning',
'NAN',
'NINF',
'NZERO',
'NaN',
'PINF',
'PZERO',
'RAISE',
'RankWarning',
'SHIFT_DIVIDEBYZERO',
'SHIFT_INVALID',
'SHIFT_OVERFLOW',
'SHIFT_UNDERFLOW',
'ScalarType',
'Tester',
'TooHardError',
'True_',
'UFUNC_BUFSIZE_DEFAULT',
'UFUNC_PYVALS_NAME',
'VisibleDeprecationWarning',
'WRAP',
'_CopyMode',
'_NoValue',
'_UFUNC_API',
'__NUMPY_SETUP__',
'__all__',
'__builtins__',
'__cached__',
'__config__',
'__deprecated_attrs__',
'__dir__',
'__doc__',
'__expired_functions__',
'__file__',
'__getattr__',
'__git_version__',
'__loader__',
'__name__',
'__package__',
'__path__',
'__spec__',
'__version__',
'_add_newdoc_ufunc',
'_distributor_init',
'_financial_names',
'_globals',
'_mat',
'_pyinstaller_hooks_dir',
'_pytesttester',
'_version',
'abs',
'absolute',
'add',
'add_docstring',
'add_newdoc',
'add_newdoc_ufunc',
'all',
'allclose',
'alltrue',
'amax',
'amin',
'angle',
'any',
'append',
'apply_along_axis',
'apply_over_axes',
'arange',
'arccos',
'arccosh',
'arcsin',
'arcsinh',
'arctan',
'arctan2',
'arctanh',
'argmax',
'argmin',
'argpartition',
'argsort',
'argwhere',
'around',
'array',
'array2string',
'array_equal',
'array_equiv',
'array_repr',
'array_split',
'array_str',
'asanyarray',
'asarray',
'asarray_chkfinite',
'ascontiguousarray',
'asfarray',
'asfortranarray',
'asmatrix',
'atleast_1d',
'atleast_2d',
'atleast_3d',
'average',
'bartlett',
'base_repr',
'binary_repr',
'bincount',
'bitwise_and',
'bitwise_not',
'bitwise_or',
'bitwise_xor',
'blackman',
'block',
'bmat',
'bool8',
'bool_',
'broadcast',
'broadcast_arrays',
'broadcast_shapes',
'broadcast_to',
'busday_count',
'busday_offset',
'busdaycalendar',
'byte',
'byte_bounds',
'bytes0',
'bytes_',
'c_',
'can_cast',
'cast',
'cbrt',
'cdouble',
'ceil',
'cfloat',
'char',
'character',
'chararray',
'choose',
'clip',
'clongdouble',
'clongfloat',
'column_stack',
'common_type',
'compare_chararrays',
'compat',
'complex128',
'complex64',
'complex_',
'complexfloating',
'compress',
'concatenate',
'conj',
'conjugate',
'convolve',
'copy',
'copysign',
'copyto',
'core',
'corrcoef',
'correlate',
'cos',
'cosh',
'count_nonzero',
'cov',
'cross',
'csingle',
'ctypeslib',
'cumprod',
'cumproduct',
'cumsum',
'datetime64',
'datetime_as_string',
'datetime_data',
'deg2rad',
'degrees',
'delete',
'deprecate',
'deprecate_with_doc',
'diag',
'diag_indices',
'diag_indices_from',
'diagflat',
'diagonal',
'diff',
'digitize',
'disp',
'divide',
'divmod',
'dot',
'double',
'dsplit',
'dstack',
'dtype',
'e',
'ediff1d',
'einsum',
'einsum_path',
'emath',
'empty',
'empty_like',
'equal',
'errstate',
'euler_gamma',
'exp',
'exp2',
'expand_dims',
'expm1',
'extract',
'eye',
'fabs',
'fastCopyAndTranspose',
'fft',
'fill_diagonal',
'find_common_type',
'finfo',
'fix',
'flatiter',
'flatnonzero',
'flexible',
'flip',
'fliplr',
'flipud',
'float16',
'float32',
'float64',
'float_',
'float_power',
'floating',
'floor',
'floor_divide',
'fmax',
'fmin',
'fmod',
'format_float_positional',
'format_float_scientific',
'format_parser',
'frexp',
'from_dlpack',
'frombuffer',
'fromfile',
'fromfunction',
'fromiter',
'frompyfunc',
'fromregex',
'fromstring',
'full',
'full_like',
'gcd',
'generic',
'genfromtxt',
'geomspace',
'get_array_wrap',
'get_include',
'get_printoptions',
'getbufsize',
'geterr',
'geterrcall',
'geterrobj',
'gradient',
'greater',
'greater_equal',
'half',
'hamming',
'hanning',
'heaviside',
'histogram',
'histogram2d',
'histogram_bin_edges',
'histogramdd',
'hsplit',
'hstack',
'hypot',
'i0',
'identity',
'iinfo',
'imag',
'in1d',
'index_exp',
'indices',
'inexact',
'inf',
'info',
'infty',
'inner',
'insert',
'int0',
'int16',
'int32',
'int64',
'int8',
'int_',
'intc',
'integer',
'interp',
'intersect1d',
'intp',
'invert',
'is_busday',
'isclose',
'iscomplex',
'iscomplexobj',
'isfinite',
'isfortran',
'isin',
'isinf',
'isnan',
'isnat',
'isneginf',
'isposinf',
'isreal',
'isrealobj',
'isscalar',
'issctype',
'issubclass_',
'issubdtype',
'issubsctype',
'iterable',
'ix_',
'kaiser',
'kron',
'lcm',
'ldexp',
'left_shift',
'less',
'less_equal',
'lexsort',
'lib',
'linalg',
'linspace',
'little_endian',
'load',
'loadtxt',
'log',
'log10',
'log1p',
'log2',
'logaddexp',
'logaddexp2',
'logical_and',
'logical_not',
'logical_or',
'logical_xor',
'logspace',
'longcomplex',
'longdouble',
'longfloat',
'longlong',
'lookfor',
'ma',
'mask_indices',
'mat',
'math',
'matmul',
'matrix',
'matrixlib',
'max',
'maximum',
'maximum_sctype',
'may_share_memory',
'mean',
'median',
'memmap',
'meshgrid',
'mgrid',
'min',
'min_scalar_type',
'minimum',
'mintypecode',
'mod',
'modf',
'moveaxis',
'msort',
'multiply',
'nan',
'nan_to_num',
'nanargmax',
'nanargmin',
'nancumprod',
'nancumsum',
'nanmax',
'nanmean',
'nanmedian',
'nanmin',
'nanpercentile',
'nanprod',
'nanquantile',
'nanstd',
'nansum',
'nanvar',
'nbytes',
'ndarray',
'ndenumerate',
'ndim',
'ndindex',
'nditer',
'negative',
'nested_iters',
'newaxis',
'nextafter',
'nonzero',
'not_equal',
'numarray',
'number',
'obj2sctype',
'object0',
'object_',
'ogrid',
'oldnumeric',
'ones',
'ones_like',
'os',
'outer',
'packbits',
'pad',
'partition',
'percentile',
'pi',
'piecewise',
'place',
'poly',
'poly1d',
'polyadd',
'polyder',
'polydiv',
'polyfit',
'polyint',
'polymul',
'polynomial',
'polysub',
'polyval',
'positive',
'power',
'printoptions',
'prod',
'product',
'promote_types',
'ptp',
'put',
'put_along_axis',
'putmask',
'quantile',
'r_',
'rad2deg',
'radians',
'random',
'ravel',
'ravel_multi_index',
'real',
'real_if_close',
'rec',
'recarray',
'recfromcsv',
'recfromtxt',
'reciprocal',
'record',
'remainder',
'repeat',
'require',
'reshape',
'resize',
'result_type',
'right_shift',
'rint',
'roll',
'rollaxis',
'roots',
'rot90',
'round',
'round_',
'row_stack',
's_',
'safe_eval',
'save',
'savetxt',
'savez',
'savez_compressed',
'sctype2char',
'sctypeDict',
'sctypes',
'searchsorted',
'select',
'set_numeric_ops',
'set_printoptions',
'set_string_function',
'setbufsize',
'setdiff1d',
'seterr',
'seterrcall',
'seterrobj',
'setxor1d',
'shape',
'shares_memory',
'short',
'show_config',
'sign',
'signbit',
'signedinteger',
'sin',
'sinc',
'single',
'singlecomplex',
'sinh',
'size',
'sometrue',
'sort',
'sort_complex',
'source',
'spacing',
'split',
'sqrt',
'square',
'squeeze',
'stack',
'std',
'str0',
'str_',
'string_',
'subtract',
'sum',
'swapaxes',
'sys',
'take',
'take_along_axis',
'tan',
'tanh',
'tensordot',
'test',
'testing',
'tile',
'timedelta64',
'trace',
'tracemalloc_domain',
'transpose',
'trapz',
'tri',
'tril',
'tril_indices',
'tril_indices_from',
'trim_zeros',
'triu',
'triu_indices',
'triu_indices_from',
'true_divide',
'trunc',
'typecodes',
'typename',
'ubyte',
'ufunc',
'uint',
'uint0',
'uint16',
'uint32',
'uint64',
'uint8',
'uintc',
'uintp',
'ulonglong',
'unicode_',
'union1d',
'unique',
'unpackbits',
'unravel_index',
'unsignedinteger',
'unwrap',
'use_hugepage',
'ushort',
'vander',
'var',
'vdot',
'vectorize',
'version',
'void',
'void0',
'vsplit',
'vstack',
'warnings',
'where',
'who',
'zeros',
'zeros_like']
In [93]: import numpy as np
array=np.arange(30,71,2)
print("Array of all the even integers from 30 to 70")
print(array)
print(array.shape)
print(array.dtype)
print(array.size)

Array of all the even integers from 30 to 70


[30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70]
(21,)
int32
21

In [ ]:

In [94]: x=np.array([[1,20,3],[14,5,6],[7,8,19]])
x

Out[94]: array([[ 1, 20, 3],


[14, 5, 6],
[ 7, 8, 19]])

In [95]: x.argmax(axis=0)

Out[95]: array([1, 0, 2], dtype=int64)

In [96]: x.argmax(axis=1)

Out[96]: array([1, 0, 2], dtype=int64)

In [97]: x.argmin(axis=0)

Out[97]: array([0, 1, 0], dtype=int64)

In [98]: x.argmin(axis=1)

Out[98]: array([0, 1, 0], dtype=int64)

In [99]: x.argsort(axis=1)

Out[99]: array([[0, 2, 1],


[1, 2, 0],
[0, 1, 2]], dtype=int64)

In [100… x.argsort(axis=0)

Out[100]: array([[0, 1, 0],


[2, 2, 1],
[1, 0, 2]], dtype=int64)

In [ ]:

You might also like