2/19/2022

Download VStack For Mac 1.2.0

Impressive Apple device manager

iTunes is the norm for managing content from your Apple device, but it doesn’t work for all people. This is where third-party manager iMazing comes in.

Our array is: 3 1 2 Applying argsort to x: 1 2 0 Reconstruct original array in sorted order: 1 2 3 Reconstruct the original array using loop: 1 2 3 numpy.lexsort function performs an indirect sort using a sequence of keys. The keys can be seen as a column in a spreadsheet. Twake is a secure program with loads of communication tools for teams. From This one program, you can share documents via group or private chat, sync your email accounts, manage files, and organize your work. To get started, just download Twake and join or create an organization.

Quick wireless transfers

iMazing is a transfer software program that lets you quickly move your media content from your iPhone, iPod or iPad to your computer.

iMazing transfers your media content from a mobile device to a desktop wirelessly or using a cable. Both options are quick and seamless.

The program also performs backups. All you need to do is connect both gadgets to the same WiFi network and schedule an automatic backup, with or without encryption.

iMazing can also access your message and browser history, contacts, and calendar, and export them in various formats.

The final major feature is the app manager. The program lets you install and uninstall apps from your Mac.

Other handy functions include a battery manager, warranty checker, simple image converter, and more.

You'll find all these on a sleek user interface with your iPhone data on the left and other functions on the right. All transfers take place live to give you full control of the process.

Where can you run this program?

iMazing is compatible with Mac and Windows PCs running on macOS 10.9 and Windows 7 or higher.

Is there a better alternative?

No, iMazing is excellent. However, if you’re interested in iOS management apps, iExplorer and WALTR are fantastic paid options. 3uTools is another alternative program that performs similar functions for free.

Our take

iMazing is an extremely well-executed, smooth, and comprehensive utility. The bundle of tools covers all iOS data-related needs. However, it costs a bit more than necessary.

Should you download it?

Yes, if you can afford the one-time purchase.

Highs

  • Packed with handy tools
  • Sleek UI
  • Automatic backup
  • Excellent customer support
  • NumPy Tutorial
  • NumPy Useful Resources
  • Selected Reading

NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional array objects and a collection of routines for processing of array.

Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also developed, having some additional functionalities. In 2005, Travis Oliphant created NumPy package by incorporating the features of Numarray into Numeric package. There are many contributors to this open source project.

Operations using NumPy

Using NumPy, a developer can perform the following operations −

  • Mathematical and logical operations on arrays.

  • Fourier transforms and routines for shape manipulation.

  • Operations related to linear algebra. NumPy has in-built functions for linear algebra and random number generation.

NumPy – A Replacement for MatLab

NumPy is often used along with packages like SciPy (Scientific Python) and Mat−plotlib (plotting library). This combination is widely used as a replacement for MatLab, a popular platform for technical computing. However, Python alternative to MatLab is now seen as a more modern and complete programming language.

It is open source, which is an added advantage of NumPy.

Standard Python distribution doesn't come bundled with NumPy module. A lightweight alternative is to install NumPy using popular Python package installer, pip.

The best way to enable NumPy is to use an installable binary package specific to your operating system. These binaries contain full SciPy stack (inclusive of NumPy, SciPy, matplotlib, IPython, SymPy and nose packages along with core Python).

Windows

Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac.

Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac.

Python (x,y): It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from https://www.python-xy.github.io/)

Linux

Package managers of respective Linux distributions are used to install one or more packages in SciPy stack.

For Ubuntu

For Fedora

Building from Source

Core Python (2.6.x, 2.7.x and 3.2.x onwards) must be installed with distutils and zlib module should be enabled.

GNU gcc (4.2 and above) C compiler must be available.

To install NumPy, run the following command.

To test whether NumPy module is properly installed, try to import it from Python prompt.

If it is not installed, the following error message will be displayed.

Alternatively, NumPy package is imported using the following syntax −

The most important object defined in NumPy is an N-dimensional array type called ndarray. It describes the collection of items of the same type. Items in the collection can be accessed using a zero-based index.

Every item in an ndarray takes the same size of block in the memory. Each element in ndarray is an object of or '>' to data type. '<' means that encoding is little-endian (least significant is stored in smallest address). '>' means that encoding is big-endian (most significant byte is stored in smallest address).

A dtype object is constructed using the following syntax −

The parameters are −

  • Object − To be converted to data type object

  • Align − If true, adds padding to the field to make it similar to C-struct

  • Copy − Makes a new copy of dtype object. If false, the result is reference to builtin data type object

Example 1

The output is as follows −

Example 2

The output is as follows −

Example 3

The output is as follows −

The following examples show the use of structured data type. Here, the field name and the corresponding scalar data type is to be declared.

Example 4

The output is as follows −

Example 5

The output is as follows −

Example 6

The output is as follows −

Example 7

The following examples define a structured data type called student with a string field 'name', an integer field 'age' and a float field 'marks'. This dtype is applied to ndarray object.

The output is as follows −

Example 8

The output is as follows −

Each built-in data type has a character code that uniquely identifies it.

  • 'b' − boolean

  • 'i' − (signed) integer

  • 'u' − unsigned integer

  • 'f' − floating-point

  • 'c' − complex-floating point

  • 'm' − timedelta

  • 'M' − datetime

  • 'O' − (Python) objects

  • 'S', 'a' − (byte-)string

  • 'U' − Unicode

  • 'V' − raw data (void)

In this chapter, we will discuss the various array attributes of NumPy.

ndarray.shape

This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.

Example 1

The output is as follows −

Example 2

The output is as follows −

Example 3

NumPy also provides a reshape function to resize an array.

The output is as follows −

ndarray.ndim

This array attribute returns the number of array dimensions.

Example 1

The output is as follows −

Example 2

The output is as follows −

numpy.itemsize

This array attribute returns the length of each element of array in bytes.

Example 1

The output is as follows −

Example 2

The output is as follows −

numpy.flags

The ndarray object has the following attributes. Its current values are returned by this function.

Sr.No.Attribute & Description
1

C_CONTIGUOUS (C)

The data is in a single, C-style contiguous segment

2

F_CONTIGUOUS (F)

The data is in a single, Fortran-style contiguous segment

3

OWNDATA (O)

The array owns the memory it uses or borrows it from another object

4

WRITEABLE (W)

The data area can be written to. Setting this to False locks the data, making it read-only

5

ALIGNED (A)

The data and all elements are aligned appropriately for the hardware

6

UPDATEIFCOPY (U)

This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array

Example

The following example shows the current values of flags.

The output is as follows −

A new ndarray object can be constructed by any of the following array creation routines or using a low-level ndarray constructor.

numpy.empty

It creates an uninitialized array of specified shape and dtype. It uses the following constructor −

The constructor takes the following parameters.

Sr.No.Parameter & Description
1

Shape

Shape of an empty array in int or tuple of int

2

Dtype

Desired output data type. Optional

3

Order

'C' for C-style row-major array, 'F' for FORTRAN style column-major array

Example

The following code shows an example of an empty array.

The output is as follows −

Note − The elements in an array show random values as they are not initialized.

numpy.zeros

Returns a new array of specified size, filled with zeros.

The constructor takes the following parameters.

Sr.No.Parameter & Description
1

Shape

Shape of an empty array in int or sequence of int

2

Dtype

Desired output data type. Optional

3

Order

'C' for C-style row-major array, 'F' for FORTRAN style column-major array

Example 1

The output is as follows −

Example 2

Now, the output would be as follows −

Example 3

It should produce the following output −

numpy.ones

Returns a new array of specified size and type, filled with ones.

The constructor takes the following parameters.

Sr.No.Parameter & Description
1

Shape

Shape of an empty array in int or tuple of int

2

Dtype

Desired output data type. Optional

3

Order

'C' for C-style row-major array, 'F' for FORTRAN style column-major array

Example 1

The output is as follows −

Example 2

Now, the output would be as follows −

In this chapter, we will discuss how to create an array from existing data.

numpy.asarray

This function is similar to numpy.array except for the fact that it has fewer parameters. This routine is useful for converting Python sequence into ndarray.

The constructor takes the following parameters.

Sr.No.Parameter & Description
1

a

Input data in any form such as list, list of tuples, tuples, tuple of tuples or tuple of lists

2

dtype

By default, the data type of input data is applied to the resultant ndarray

3

order

C (row major) or F (column major). C is default

The following examples show how you can use the asarray function.

Example 1

Its output would be as follows −

Example 2

Now, the output would be as follows −

Example 3

Its output would be −

Example 4

Here, the output would be as follows −

numpy.frombuffer

This function interprets a buffer as one-dimensional array. Any object that exposes the buffer interface is used as parameter to return an ndarray.

The constructor takes the following parameters.

Sr.No.Parameter & Description
1

buffer

Any object that exposes buffer interface

2

dtype

Data type of returned ndarray. Defaults to float

3

count

The number of items to read, default -1 means all data

4

offset

The starting position to read from. Default is 0

Example

The following examples demonstrate the use of frombuffer function.

Here is its output −

numpy.fromiter

This function builds an ndarray object from any iterable object. A new one-dimensional array is returned by this function.

Here, the constructor takes the following parameters.

Sr.No.Parameter & Description
1

iterable

Any iterable object

2

dtype

Data type of resultant array

3

count

The number of items to be read from iterator. Default is -1 which means all data to be read

The following examples show how to use the built-in range() function to return a list object. An iterator of this list is used to form an ndarray object.

Example 1

Its output is as follows −

Example 2

Now, the output would be as follows −

In this chapter, we will see how to create an array from numerical ranges.

numpy.arange

This function returns an ndarray object containing evenly spaced values within a given range. The format of the function is as follows −

The constructor takes the following parameters.

Sr.No.Parameter & Description
1

start

The start of an interval. If omitted, defaults to 0

2

stop

The end of an interval (not including this number)

3

step

Spacing between values, default is 1

4

dtype

Data type of resulting ndarray. If not given, data type of input is used

The following examples show how you can use this function.

Example 1

Its output would be as follows −

Example 2

Here, the output would be −

Example 3

Its output is as follows −

numpy.linspace

This function is similar to arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified. The usage of this function is as follows −

The constructor takes the following parameters.

Sr.No.Parameter & Description
1

start

The starting value of the sequence

2

stop

The end value of the sequence, included in the sequence if endpoint set to true

3

num

The number of evenly spaced samples to be generated. Default is 50

4

endpoint

True by default, hence the stop value is included in the sequence. If false, it is not included

5

retstep

If true, returns samples and step between the consecutive numbers

6

dtype

Data type of output ndarray

The following examples demonstrate the use linspace function.

Example 1

Its output would be −

Example 2

The output would be −

Example 3

Now, the output would be −

numpy.logspace

This function returns an ndarray object that contains the numbers that are evenly spaced on a log scale. Start and stop endpoints of the scale are indices of the base, usually 10.

Following parameters determine the output of logspace function.

Sr.No.Parameter & Description
1

start

The starting point of the sequence is basestart

2

stop

The final value of sequence is basestop

3

num

The number of values between the range. Default is 50

4

endpoint

If true, stop is the last value in the range

5

base

Base of log space, default is 10

6

dtype

Data type of output array. If not given, it depends upon other input arguments

The following examples will help you understand the logspace function.

Example 1

Its output would be as follows −

Example 2

Now, the output would be −

Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's in-built container objects.

As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing.

Basic slicing is an extension of Python's basic concept of slicing to n dimensions. A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function. This slice object is passed to the array to extract a part of array.

Example 1

Its output is as follows −

In the above example, an ndarray object is prepared by arange() function. Then a slice object is defined with start, stop, and step values 2, 7, and 2 respectively. When this slice object is passed to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced.

The same result can also be obtained by giving the slicing parameters separated by a colon : (start:stop:step) directly to the ndarray object.

Example 2

Here, we will get the same output −

If only one parameter is put, a single item corresponding to the index will be returned. If a : is inserted in front of it, all items from that index onwards will be extracted. If two parameters (with : between them) is used, items between the two indexes (not including the stop index) with default step one are sliced.

Example 3

Its output is as follows −

Example 4

Now, the output would be −

Example 5

Here, the output would be −

The above description applies to multi-dimensional ndarray too.

Example 6

The output is as follows −

Slicing can also include ellipsis (…) to make a selection tuple of the same length as the dimension of an array. If ellipsis is used at the row position, it will return an ndarray comprising of items in rows.

Example 7

The output of this program is as follows −

Download VStack For Mac 1.2.0 Gratis

It is possible to make a selection from ndarray that is a non-tuple sequence, ndarray object of integer or Boolean data type, or a tuple with at least one item being a sequence object. Advanced indexing always returns a copy of the data. As against this, the slicing only presents a view.

There are two types of advanced indexing − Integer and Boolean.

Integer Indexing

This mechanism helps in selecting any arbitrary item in an array based on its N-dimensional index. Each integer array represents the number of indexes into that dimension. When the index consists of as many integer arrays as the dimensions of the target ndarray, it becomes straightforward.

In the following example, one element of specified column from each row of ndarray object is selected. Hence, the row index contains all row numbers, and the column index specifies the element to be selected.

Example 1

Its output would be as follows −

The selection includes elements at (0,0), (1,1) and (2,0) from the first array.

In the following example, elements placed at corners of a 4X3 array are selected. The row indices of selection are [0, 0] and [3,3] whereas the column indices are [0,2] and [0,2].

Example 2

The output of this program is as follows −

The resultant selection is an ndarray object containing corner elements.

Advanced and basic indexing can be combined by using one slice (:) or ellipsis (…) with an index array. The following example uses slice for row and advanced index for column. The result is the same when slice is used for both. But advanced index results in copy and may have different memory layout.

Example 3

The output of this program would be as follows −

Boolean Array Indexing

This type of advanced indexing is used when the resultant object is meant to be the result of Boolean operations, such as comparison operators.

Example 1

In this example, items greater than 5 are returned as a result of Boolean indexing.

The output of this program would be −

Example 2

In this example, NaN (Not a Number) elements are omitted by using ~ (complement operator).

Its output would be −

Example 3

The following example shows how to filter out the non-complex elements from an array.

Here, the output is as follows −

The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.

Example 1

Its output is as follows −

If the dimensions of two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. The smaller array is broadcast to the size of the larger array so that they have compatible shapes.

Broadcasting is possible if the following rules are satisfied −

  • Array with smaller ndim than the other is prepended with '1' in its shape.

  • Size in each dimension of the output shape is maximum of the input sizes in that dimension.

  • An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1.

  • If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

A set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true −

  • Arrays have exactly the same shape.

  • Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.

  • Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.

The following program shows an example of broadcasting.

Example 2

The output of this program would be as follows −

The following figure demonstrates how array b is broadcast to become compatible with a.

NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface.

Let us create a 3X4 array using arange() function and iterate over it using nditer.

Example 1

The output of this program is as follows −

Example 2

The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array.

The output of the above program is as follows −

Iteration Order

If the same elements are stored using F-style order, the iterator chooses the more efficient way of iterating over an array.

Example 1

Its output would be as follows −

Example 2

It is possible to force nditer object to use a specific order by explicitly mentioning it.

Its output would be −

Modifying Array Values

The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator.

Example

Its output is as follows −

External Loop

The nditer class constructor has a ‘flags’ parameter, which can take the following values −

Sr.No.Parameter & Description
1

c_index

C_order index can be tracked

2

f_index

Fortran_order index is tracked

3

multi-index

Type of indexes with one per iteration can be tracked

4

external_loop

Causes values given to be one-dimensional arrays with multiple values instead of zero-dimensional array

Example

In the following example, one-dimensional arrays corresponding to each column is traversed by the iterator.

The output is as follows −

Broadcasting Iteration

If two arrays are broadcastable, a combined nditer object is able to iterate upon them concurrently. Assuming that an array a has dimension 3X4, and there is another array b of dimension 1X4, the iterator of following type is used (array b is broadcast to size of a).

Example

Its output would be as follows −

Several routines are available in NumPy package for manipulation of elements in ndarray object. They can be classified into the following types −

Changing Shape

Sr.No.Shape & Description
1reshape

Gives a new shape to an array without changing its data

2flat

A 1-D iterator over the array

3flatten

Returns a copy of the array collapsed into one dimension

4ravel

Returns a contiguous flattened array

Transpose Operations

Sr.No.Operation & Description
1transpose

Permutes the dimensions of an array

2ndarray.T

Same as self.transpose()

3rollaxis

Rolls the specified axis backwards

4swapaxes

Interchanges the two axes of an array

Changing Dimensions

Sr.No.Dimension & Description
1broadcast

Produces an object that mimics broadcasting

2broadcast_to

Broadcasts an array to a new shape

3expand_dims

Expands the shape of an array

4squeeze

Removes single-dimensional entries from the shape of an array

Joining Arrays

Sr.No.Array & Description
1concatenate

Joins a sequence of arrays along an existing axis

2stack

Joins a sequence of arrays along a new axis

3hstack

Stacks arrays in sequence horizontally (column wise)

4vstack

Stacks arrays in sequence vertically (row wise)

Splitting Arrays

Sr.No.Array & Description
1split

Splits an array into multiple sub-arrays

2hsplit

Splits an array into multiple sub-arrays horizontally (column-wise)

3vsplit

Splits an array into multiple sub-arrays vertically (row-wise)

Adding / Removing Elements

Sr.No.Element & Description
1resize

Returns a new array with the specified shape

2append

Appends the values to the end of an array

3insert

Inserts the values along the given axis before the given indices

4delete

Returns a new array with sub-arrays along an axis deleted

5unique

Finds the unique elements of an array

Following are the functions for bitwise operations available in NumPy package.

Sr.No.Operation & Description
1bitwise_and

Computes bitwise AND operation of array elements

2bitwise_or

Computes bitwise OR operation of array elements

3invert

Computes bitwise NOT

4left_shift

Shifts bits of a binary representation to the left

5right_shift

Shifts bits of binary representation to the right

The following functions are used to perform vectorized string operations for arrays of dtype numpy.string_ or numpy.unicode_. They are based on the standard string functions in Python's built-in library.

Sr.No.Function & Description
1add()

Returns element-wise string concatenation for two arrays of str or Unicode

2multiply()

Returns the string with multiple concatenation, element-wise

3center()

Returns a copy of the given string with elements centered in a string of specified length

4capitalize()

Returns a copy of the string with only the first character capitalized

5title()

Returns the element-wise title cased version of the string or unicode

6lower()

Returns an array with the elements converted to lowercase

7upper()

Returns an array with the elements converted to uppercase

8split()

Returns a list of the words in the string, using separatordelimiter

9splitlines()

Returns a list of the lines in the element, breaking at the line boundaries

10strip()

Returns a copy with the leading and trailing characters removed

11join()

Returns a string which is the concatenation of the strings in the sequence

12replace()

Returns a copy of the string with all occurrences of substring replaced by the new string

13decode()

Calls str.decode element-wise

14encode()

Calls str.encode element-wise

These functions are defined in character array class (numpy.char). The older Numarray package contained chararray class. The above functions in numpy.char class are useful in performing vectorized string operations.

Quite understandably, NumPy contains a large number of various mathematical operations. NumPy provides standard trigonometric functions, functions for arithmetic operations, handling complex numbers, etc.

Trigonometric Functions

NumPy has standard trigonometric functions which return trigonometric ratios for a given angle in radians.

Example

Here is its output −

arcsin, arcos, and arctan functions return the trigonometric inverse of sin, cos, and tan of the given angle. The result of these functions can be verified by numpy.degrees() function by converting radians to degrees.

Example

Its output is as follows −

Functions for Rounding

numpy.around()

This is a function that returns the value rounded to the desired precision. The function takes the following parameters.

Where,

Sr.No.Parameter & Description
1

a

Input data

2

decimals

The number of decimals to round to. Default is 0. If negative, the integer is rounded to position to the left of the decimal point

Example

It produces the following output −

numpy.floor()

This function returns the largest integer not greater than the input parameter. The floor of the scalar x is the largest integer i, such that i <= x. Note that in Python, flooring always is rounded away from 0.

Example

It produces the following output −

numpy.ceil()

The ceil() function returns the ceiling of an input value, i.e. the ceil of the scalar x is the smallest integer i, such that i >= x.

Example

It will produce the following output −

Input arrays for performing arithmetic operations such as add(), subtract(), multiply(), and divide() must be either of the same shape or should conform to array broadcasting rules.

Example

It will produce the following output −

Let us now discuss some of the other important arithmetic functions available in NumPy.

numpy.reciprocal()

This function returns the reciprocal of argument, element-wise. For elements with absolute values larger than 1, the result is always 0 because of the way in which Python handles integer division. For integer 0, an overflow warning is issued.

Example

It will produce the following output −

numpy.power()

This function treats elements in the first input array as base and returns it raised to the power of the corresponding element in the second input array.

It will produce the following output −

numpy.mod()

This function returns the remainder of division of the corresponding elements in the input array. The function numpy.remainder() also produces the same result.

It will produce the following output −

The following functions are used to perform operations on array with complex numbers.

  • numpy.real() − returns the real part of the complex data type argument.

  • numpy.imag() − returns the imaginary part of the complex data type argument.

  • numpy.conj() − returns the complex conjugate, which is obtained by changing the sign of the imaginary part.

  • numpy.angle() − returns the angle of the complex argument. The function has degree parameter. If true, the angle in the degree is returned, otherwise the angle is in radians.

It will produce the following output −

NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc. from the given elements in the array. The functions are explained as follows −

numpy.amin() and numpy.amax()

These functions return the minimum and the maximum from the elements in the given array along the specified axis.

Example

It will produce the following output −

numpy.ptp()

The numpy.ptp() function returns the range (maximum-minimum) of values along an axis.

It will produce the following output −

numpy.percentile()

Percentile (or a centile) is a measure used in statistics indicating the value below which a given percentage of observations in a group of observations fall. The function numpy.percentile() takes the following arguments.

Where,

Sr.No.Argument & Description
1

a

Input array

2

q

The percentile to compute must be between 0-100

3

axis

The axis along which the percentile is to be calculated

Example

It will produce the following output −

numpy.median()

Median is defined as the value separating the higher half of a data sample from the lower half. The numpy.median() function is used as shown in the following program.

Example

It will produce the following output −

numpy.mean()

Arithmetic mean is the sum of elements along an axis divided by the number of elements. The numpy.mean() function returns the arithmetic mean of elements in the array. If the axis is mentioned, it is calculated along it.

Example

It will produce the following output −

numpy.average()

Weighted average is an average resulting from the multiplication of each component by a factor reflecting its importance. The numpy.average() function computes the weighted average of elements in an array according to their respective weight given in another array. The function can have an axis parameter. If the axis is not specified, the array is flattened.

Considering an array [1,2,3,4] and corresponding weights [4,3,2,1], the weighted average is calculated by adding the product of the corresponding elements and dividing the sum by the sum of weights.

Weighted average = (1*4+2*3+3*2+4*1)/(4+3+2+1)

Example

It will produce the following output −

In a multi-dimensional array, the axis for computation can be specified.

Example

It will produce the following output −

Standard Deviation

Standard deviation is the square root of the average of squared deviations from mean. The formula for standard deviation is as follows −

If the array is [1, 2, 3, 4], then its mean is 2.5. Hence the squared deviations are [2.25, 0.25, 0.25, 2.25] and the square root of its mean divided by 4, i.e., sqrt (5/4) is 1.1180339887498949.

Example

It will produce the following output −

Variance

Variance is the average of squared deviations, i.e., mean(abs(x - x.mean())**2). In other words, the standard deviation is the square root of variance.

Example

It will produce the following output −

A variety of sorting related functions are available in NumPy. These sorting functions implement different sorting algorithms, each of them characterized by the speed of execution, worst case performance, the workspace required and the stability of algorithms. Following table shows the comparison of three sorting algorithms.

kindspeedworst casework spacestable
‘quicksort’1O(n^2)0no
‘mergesort’2O(n*log(n))~n/2yes
‘heapsort’3O(n*log(n))0no

numpy.sort()

The sort() function returns a sorted copy of the input array. It has the following parameters −

Where,

Sr.No.Parameter & Description
1

a

Array to be sorted

2

axis

The axis along which the array is to be sorted. If none, the array is flattened, sorting on the last axis

3

kind

Default is quicksort

4

order

If the array contains fields, the order of fields to be sorted

Example

It will produce the following output −

numpy.argsort()

The numpy.argsort() function performs an indirect sort on input array, along the given axis and using a specified kind of sort to return the array of indices of data. This indices array is used to construct the sorted array.

Example

It will produce the following output −

numpy.lexsort()

function performs an indirect sort using a sequence of keys. The keys can be seen as a column in a spreadsheet. The function returns an array of indices, using which the sorted data can be obtained. Note, that the last key happens to be the primary key of sort.

Example

It will produce the following output −

NumPy module has a number of functions for searching inside an array. Functions for finding the maximum, the minimum as well as the elements satisfying a given condition are available.

numpy.argmax() and numpy.argmin()

These two functions return the indices of maximum and minimum elements respectively along the given axis.

Example

It will produce the following output −

numpy.nonzero()

The numpy.nonzero() function returns the indices of non-zero elements in the input array.

Example

It will produce the following output −

numpy.where()

The where() function returns the indices of elements in an input array where the given condition is satisfied.

Example

It will produce the following output −

numpy.extract()

The extract() function returns the elements satisfying any condition.

It will produce the following output −

We have seen that the data stored in the memory of a computer depends on which architecture the CPU uses. It may be little-endian (least significant is stored in the smallest address) or big-endian (most significant byte in the smallest address).

numpy.ndarray.byteswap()

The numpy.ndarray.byteswap() function toggles between the two representations: bigendian and little-endian.

It will produce the following output −

While executing the functions, some of them return a copy of the input array, while some return the view. When the contents are physically stored in another location, it is called Copy. If on the other hand, a different view of the same memory content is provided, we call it as View.

No Copy

Simple assignments do not make the copy of array object. Instead, it uses the same id() of the original array to access it. The id() returns a universal identifier of Python object, similar to the pointer in C.

Furthermore, any changes in either gets reflected in the other. For example, the changing shape of one will change the shape of the other too.

Example

It will produce the following output −

View or Shallow Copy

NumPy has ndarray.view() method which is a new array object that looks at the same data of the original array. Unlike the earlier case, change in dimensions of the new array doesn’t change dimensions of the original.

Example

It will produce the following output −

Slice of an array creates a view.

Download VStack For Mac 1.2.0

Example

It will produce the following output −

Deep Copy

The ndarray.copy() function creates a deep copy. It is a complete copy of the array and its data, and doesn’t share with the original array.

Example

It will produce the following output −

NumPy package contains a Matrix library numpy.matlib. This module has functions that return matrices instead of ndarray objects.

matlib.empty()

The matlib.empty() function returns a new matrix without initializing the entries. The function takes the following parameters.

Where,

Sr.No.Parameter & Description
1

shape

int or tuple of int defining the shape of the new matrix

2

Dtype

Optional. Data type of the output

3

order

C or F

Example

It will produce the following output −

numpy.matlib.zeros()

This function returns the matrix filled with zeros.

It will produce the following output −

numpy.matlib.ones()

This function returns the matrix filled with 1s.

It will produce the following output −

numpy.matlib.eye()

This function returns a matrix with 1 along the diagonal elements and the zeros elsewhere. The function takes the following parameters.

Where,

Sr.No.Parameter & Description
1

n

The number of rows in the resulting matrix

2

M

The number of columns, defaults to n

3

k

Index of diagonal

4

dtype

Data type of the output

Example

It will produce the following output −

numpy.matlib.identity()

Download VStack For Mac 1.2.0 Pc

The numpy.matlib.identity() function returns the Identity matrix of the given size. An identity matrix is a square matrix with all diagonal elements as 1.

It will produce the following output −

numpy.matlib.rand()

The numpy.matlib.rand() function returns a matrix of the given size filled with random values.

Example

It will produce the following output −

Note that a matrix is always two-dimensional, whereas ndarray is an n-dimensional array. Both the objects are inter-convertible.

Example

It will produce the following output −

Example

It will produce the following output −

Example

It will produce the following output −

NumPy package contains numpy.linalg module that provides all the functionality required for linear algebra. Some of the important functions in this module are described in the following table.

Sr.No.Function & Description
1dot

Dot product of the two arrays

2vdot

Dot product of the two vectors

3inner

Inner product of the two arrays

4matmul

Matrix product of the two arrays

5determinant

Computes the determinant of the array

6solve

Solves the linear matrix equation

7inv

Finds the multiplicative inverse of the matrix

Matplotlib is a plotting library for Python. It is used along with NumPy to provide an environment that is an effective open source alternative for MatLab. It can also be used with graphics toolkits like PyQt and wxPython.

Matplotlib module was first written by John D. Hunter. Since 2012, Michael Droettboom is the principal developer. Currently, Matplotlib ver. 1.5.1 is the stable version available. The package is available in binary distribution as well as in the source code form on www.matplotlib.org.

Conventionally, the package is imported into the Python script by adding the following statement −

Here pyplot() is the most important function in matplotlib library, which is used to plot 2D data. The following script plots the equation y = 2x + 5

Example

An ndarray object x is created from np.arange() function as the values on the x axis. The corresponding values on the y axis are stored in another ndarray object y. These values are plotted using plot() function of pyplot submodule of matplotlib package.

The graphical representation is displayed by show() function.

The above code should produce the following output −

Instead of the linear graph, the values can be displayed discretely by adding a format string to the plot() function. Following formatting characters can be used.

Sr.No.Character & Description
1

'-'

Solid line style

2

'--'

Dashed line style

3

'-.'

Dash-dot line style

4

':'

Dotted line style

5

'.'

Point marker

6

','

Pixel marker

7

'o'

Circle marker

8

'v'

Triangle_down marker

9

'^'

Triangle_up marker

10

'<'

Triangle_left marker

11

'>'

Triangle_right marker

12

'1'

Tri_down marker

13

'2'

Tri_up marker

14

'3'

Tri_left marker

15

'4'

Tri_right marker

16

's'

Square marker

17

'p'

Pentagon marker

18

'*'

Star marker

19

'h'

Hexagon1 marker

20

'H'

Hexagon2 marker

21

'+'

Plus marker

22

'x'

X marker

23

'D'

Diamond marker

24

'd'

Thin_diamond marker

25

' '

Vline marker

26

'_'

Hline marker

The following color abbreviations are also defined.

CharacterColor
'b'Blue
'g'Green
'r'Red
'c'Cyan
'm'Magenta
'y'Yellow
'k'Black
'w'White

To display the circles representing points, instead of the line in the above example, use “ob” as the format string in plot() function.

Download VStack For Mac 1.2.0 Crack

Example

The above code should produce the following output −

Sine Wave Plot

The following script produces the sine wave plot using matplotlib.

Example

subplot()

The subplot() function allows you to plot different things in the same figure. In the following script, sine and cosine values are plotted.

Example

The above code should produce the following output −

bar()

The pyplot submodule provides bar() function to generate bar graphs. The following example produces the bar graph of two sets of x and y arrays.

Example

This code should produce the following output −

NumPy has a numpy.histogram() function that is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size corresponding to class interval called bin and variable height corresponding to frequency.

numpy.histogram()

The numpy.histogram() function takes the input array and bins as two parameters. The successive elements in bin array act as the boundary of each bin.

It will produce the following output −

plt()

Matplotlib can convert this numeric representation of histogram into a graph. The plt() function of pyplot submodule takes the array containing the data and bin array as parameters and converts into a histogram.

It should produce the following output −

The ndarray objects can be saved to and loaded from the disk files. The IO functions available are −

  • load() and save() functions handle /numPy binary files (with npy extension)

  • loadtxt() and savetxt() functions handle normal text files

NumPy introduces a simple file format for ndarray objects. This .npy file stores data, shape, dtype and other information required to reconstruct the ndarray in a disk file such that the array is correctly retrieved even if the file is on another machine with different architecture.

numpy.save()

The numpy.save() file stores the input array in a disk file with npy extension.

To reconstruct array from outfile.npy, use load() function.

It will produce the following output −

The save() and load() functions accept an additional Boolean parameter allow_pickles. A pickle in Python is used to serialize and de-serialize objects before saving to or reading from a disk file.

Download VStack For Mac 1.2.0 Full

savetxt()

The storage and retrieval of array data in simple text file format is done with savetxt() and loadtxt() functions.

Example

It will produce the following output −

The savetxt() and loadtxt() functions accept additional optional parameters such as header, footer, and delimiter.


Logout