Pandas have a few compelling data structures: A table with multiple columns is the DataFrame. A column of a DataFrame, or a list-like object, is called a Series. A DataFrame is a table much like in SQL or Excel. It’s similar in structure, too, making it possible to use similar operations such as aggregation, filtering, and pivoting. Pandas […]

The post Pandas where: How to Use Pandas DataFrame where() appeared first on AppDividend.

]]>Pandas have a few compelling data structures:

- A table with multiple columns is the
**DataFrame**. - A column of a DataFrame, or a list-like object, is called a
**Series**.

A **DataFrame** is a table much like in SQL or Excel. It’s similar in structure, too, making it possible to use similar operations such as aggregation, filtering, and pivoting.

Pandas where() function is used to check the DataFrame for one or more conditions and return the result accordingly. By default, the rows not satisfying the condition are filled with NaN value. The difference between the numpy where and DataFrame where is that the DataFrame supplies the default values that the where() method is being called.

DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None)

**cond: **bool Series/DataFrame, array-like, or callable

If the where cond is True, keep the original value. if the where cond False, replace with the corresponding value from others. If cond is callable, it is computed on the Series/DataFrame and returns the boolean Series/DataFrame or array.

**other: **scalar, Series/DataFrame, or callable

Entries, where cond is False, are replaced with the corresponding value from other parameters. If the other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame.

**inplace: **bool, default False

Whether to operate in place on the data.

**axis: **int, default None

Alignment axis, if needed.

**level: **int, default None

Alignment level, if needed.

**errors: **str, {‘raise’, ‘ignore’}, default ‘raise.’

Note that currently, the errors parameter won’t affect the results and will always coerce to a suitable dtype.

- ‘
**raise’**: Allow exceptions to be raised. **‘ignore’**: Suppress exceptions on error return the original object.

**try_cast: **bool, default False.

Try to cast a result back to the input type (if possible).

It returns the Same type as the caller.

See the following code.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Pedro', 'Karl Urban']} df = pd.DataFrame.from_dict(datae # filtering data filter = df["Show"] == "Mandalorian" df.where(filter, inplace=True) print(df)

Show Streaming Season Main Actor 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 Mandalorian Disney Plus 1.0 Pedro 3 NaN NaN NaN NaN

The main task of the where() method in the above example is to check the DataFrame for one condition, which is the “**show = Mandalorian,”** and it returned the output accordingly. By default, if the rows are not satisfying a condition, it is filled with **NaN** value.

You can see that in our result DataFrame, only the row which has Mandalorian value got returned, and other values are NaN.

Let’s create a series using Python range() function and use the where conditions to fetch the required values.

# app.py import pandas as pd s = pd.Series(range(5)) s.where(s > 2, inplace=True) print(s)

0 NaN 1 NaN 2 NaN 3 3.0 4 4.0 dtype: float64

As shown in the output, every row which doesn’t satisfy value > 2 is replaced with **NaN**.

To apply multiple conditions in pandas where() method, use **&** operator between the conditions.

If one condition fails, then it won’t return the actual value with DataFrame. See the following code.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) # filtering data filter = df["Show"] == "Stranger Things" filter2 = df["Season"] == 3 df.where(filter & filter2, inplace=True) print(df)

Show Streaming Season Main Actor 0 Stranger Things Netflix 3.0 Millie 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN

Now, if one condition does not satisfy, then it will return NaN values.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) # filtering data filter = df["Show"] == "Stranger Things" filter2 = df["Season"] == 12 df.where(filter & filter2, inplace=True) print(df)

In this example, the first condition satisfies **Show = Stranger Things,** but in the **filter2**, it does not satisfy the **Stranger Things **show has 12 seasons.

So, it won’t return Stranger Things row as well as The X-Files row because then the first condition will not satisfy. So, it will return the NaN values.

Show Streaming Season Main Actor 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN

You can see that due to one condition fail, and it will return a DataFrame with NaN values.

That is it for Pandas DataFrame, where() function example.

Pandas DataFrame drop_duplicates()

The post Pandas where: How to Use Pandas DataFrame where() appeared first on AppDividend.

]]>Mean Function in Pandas is used to calculate the arithmetic mean of a given set of numbers, mean of the DataFrame, column-wise mean, or mean of the column in pandas and row-wise mean or mean of rows in Pandas. Pandas mean To find mean of DataFrame, use Pandas DataFrame.mean() function. The DataFrame.mean() function returns the […]

The post Pandas mean: How to Find Mean in Pandas DataFrame appeared first on AppDividend.

]]>Mean Function in Pandas is used to calculate the arithmetic mean of a given set of numbers, mean of the DataFrame, column-wise mean, or mean of the column in pandas and row-wise mean or mean of rows in Pandas.

To find mean of DataFrame, use Pandas DataFrame.mean() function. The DataFrame.mean() function returns the mean of the values for the requested axis.

If the mean() method is applied to a Pandas series object, then it returns the scalar value, which is the mean value of all the values in the DataFrame.

If the mean() method is applied on a Pandas DataFrame object, then it returns the pandas series object that contains the mean of the values over the specified axis.

DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

**axis**{index (0), columns (1)}

Axis for the method to be applied.

**skipna: **bool, default **True**

Exclude NA/None values when computing the result.

**level: **int or level name, default None

If the axis is the **MultiIndex**, count along with a specific level, collapsing into the **Series**.

**numeric_only: **bool, default None

Include only float, int, boolean columns. If the values are **None**, will attempt to use everything, then use only numeric data. Not implemented for Series.

****kwargs**

Additional keyword arguments to be passed to the function.

It returns Series or DataFrame (if level specified).

In the df.mean() method, if we don’t specify the axis, then it will take the index axis by default.

In the below example, we will find the mean of DataFrame with reference to the index axis.

# app.py import pandas as pd data = {'X': [29, 46, 10, 36], 'Y': [11, 18, 19, 21], 'Z': [3, 12, 1, 2]} df = pd.DataFrame.from_dict(data) meanDf = df.mean() print(meanDf)

X 30.25 Y 17.25 Z 4.50 dtype: float64

In this example, we got a series of mean values with respect to the index axis. This is how it calculated.

X = 30.25, it is the output of 29 + 46 + 10 + 36 = 121. And then we need to divide it by 4, which gives 30.25. It is the same for Y and Z.

To calculate mean row-wise in the DataFrame, pass the axis = 1 parameter.

# app.py import pandas as pd data = {'X': [29, 46, 10, 36], 'Y': [11, 18, 19, 21], 'Z': [3, 12, 1, 2]} df = pd.DataFrame.from_dict(data) meanDf = df.mean(axis=1) print(meanDf)

0 14.333333 1 25.333333 2 10.000000 3 19.666667 dtype: float64

Here, inside the df.mean() function, we passed axis = 1 parameter.

The calculation of the mean function is following.

For the first row, the mean value is 14.33, which is calculated by 29 + 11 + 3 = 43 and then divide that by 3, which gives 14.33. This calculation is the same for the second, third, and fourth row.

The df.mean(axis=0), axis=0 argument calculates the column-wise mean of the dataframe so that the result will be axis=1 is row-wise mean, so you are getting multiple values.

So, if you want to calculate mean values, row-wise, or column-wise, you need to pass the appropriate axis. Otherwise, by default, it will give you index based mean.

There are times when you face lots of None or NaN values in the DataFrame. When we encounter that, we can find the mean value over the column axis.

See the following code.

# app.py import pandas as pd data = {'X': [29, 46, None, 36], 'Y': [11, None, 19, 21], 'Z': [3, 12, 1, None]} df = pd.DataFrame.from_dict(data) meanDf = df.mean(axis=1, skipna=True) print(meanDf)

0 14.333333 1 29.000000 2 10.000000 3 28.500000 dtype: float64

To find a mean of specific DataFrame column, use **df**[**“column name”**].

# app.py import pandas as pd data = {'X': [29, 46, None, 36], 'Y': [11, None, 19, 21], 'Z': [3, 12, 1, None]} df = pd.DataFrame.from_dict(data) meanZ = df['Z'].mean() print(meanZ)

5.333333333333333

In this example, we got the mean of column Z, which contains **None** values as well.

The output is calculated like this: 3 + 12 + 1 = 16 and then divide that by 3 which is the final output = **5.3333.**

To calculate a mean of the Pandas DataFrame, you can use pandas.DataFrame.mean() method. Using the mean() method, you can calculate mean along an axis, or the complete DataFrame. Just remember the following points.

df.mean(axis=0)

df.mean(axis=1)

That is it for Pandas DataFrame mean() function.

The post Pandas mean: How to Find Mean in Pandas DataFrame appeared first on AppDividend.

]]>Pandas DataFrame drop() method allows us to remove columns and rows from the DataFrame object. Pandas Drop Column To drop or remove the column in DataFrame, use the Pandas DataFrame drop() method. The df.Drop() method deletes specified labels from rows or columns. It removes the rows or columns by specifying label names and corresponding axis, […]

The post Pandas Drop Column: How to Drop Column in DataFrame appeared first on AppDividend.

]]>Pandas DataFrame drop() method allows us to remove columns and rows from the DataFrame object.

To drop or remove the column in DataFrame, use the Pandas DataFrame drop() method. The df.Drop() method deletes specified labels from rows or columns. It removes the rows or columns by specifying label names and corresponding axis, or by specifying index or column names directly.

When using a multi-index, labels on different levels can be removed by specifying the level.

DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

**labels**: single label or list-like

Index or column labels to drop.

**axis**{0 or ‘index’, 1 or ‘columns’}, default 0

Whether to drop labels from an index (0 or ‘index’) or columns (1 or ‘columns’).

**index**: single label or list-like

Alternative to defining the axis (labels, axis=0 is equivalent to index=labels).

**columns**: single label or list-like

Alternative to specifying axis (labels, axis=1 is equivalent to columns=labels).

**level**: int or level name, optional

For MultiIndex, the level from which the labels will be removed.

**inplace**: bool, default False

If False, return a copy. Otherwise, do operation **inplace** and returns None.

**errors{‘ignore’, ‘raise’}**, default ‘**raise**’.

If ‘**ignore**’, suppress error, and only existing labels are dropped.

The drop() function returns the DataFrame without the removed index or column labels.

The drop() method can raise the KeyError If any of the labels are not found in the selected axis.

Drop one or more than one column from the DataFrame can be achieved in multiple ways.

- To drop columns in DataFrame, use the df.drop() method.
- Drop columns from a DataFrame using iloc[ ] and drop() method.
- Drop columns from a DataFrame using loc[ ] and drop() method.

To create a DataFrame from Dictionary, use the pd.DataFrame.from_dict() function.

import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) print(df)

Show Streaming Season Main Actor 0 Stranger Things Netflix 3 Millie 1 The X-Files Fx 12 Gillian 2 Mandalorian Disney Plus 1 Padro 3 The Boys Amazon Prime 2 Karl Urban

You can see that DataFrame is created with four rows and four columns.

To drop a single column from DataFrame, use the drop() method and pass only one column in the columns list like below.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) df.drop(columns=['Season'], inplace=True) print(df)

python3 app.py Show Streaming Main Actor 0 Stranger Things Netflix Millie 1 The X-Files Fx Gillian 2 Mandalorian Disney Plus Padro 3 The Boys Amazon Prime Karl Urban

You can see that we tried to remove the **Season** column, and it does remove the column.

To remove multiple columns from DataFrame, pass the list of columns that needs to be removed while using the drop() function.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) df.drop(columns=['Season', 'Streaming'], inplace=True) print(df)

python3 app.py Show Main Actor 0 Stranger Things Millie 1 The X-Files Gillian 2 Mandalorian Padro 3 The Boys Karl Urban

You can see that we passed a list of columns like Season and Streaming, and in the output, it is removed from the DataFrame.

To remove columns as index base, use df.columns() function.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) df.drop(df.columns[[1, 2]], axis=1, inplace=True) print(df)

In this example, we want to remove the column index 1 and 2, which is **Streaming **and **Season. **So, we are eliminating the columns using column index using df.columns[] property and pass the column indexes to the list.

To remove all the columns between the specific columns, use the iloc[ ] and drop() method.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) df.drop(df.iloc[:, 1:3], inplace=True, axis=1) print(df)

python3 app.py Show Main Actor 0 Stranger Things Millie 1 The X-Files Gillian 2 Mandalorian Padro 3 The Boys Karl Urban

Pandas.DataFrame.iloc is the unique inbuilt property that returns integer-location based indexing for selection by position. We use this function to get the index of the column and then pass that to the drop() method and remove the columns based on the indices.

Pandas DataFrame loc[] is used to access the group of rows and columns by labels or a Boolean array. See the following code.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) df.drop(df.loc[:, 'Streaming':'Season'].columns, axis=1, inplace=True) print(df)

python3 app.py Show Main Actor 0 Stranger Things Millie 1 The X-Files Gillian 2 Mandalorian Padro 3 The Boys Karl Urban

In this example, we use the loc[ ] method to group the columns and remove those columns from the DataFrame using the df.drop() method.

The Difference between **loc( )** and **iloc( )** is that **iloc( )** excludes the last column range element.

If the DataFrame doesn’t contain the given labels, KeyError is raised.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) df.drop(columns=['ABC']) print(df)

python3 app.py Traceback (most recent call last): KeyError: "['ABC'] not found in axis"

We can suppress this error by specifying errors=’ignore’ in the drop() function call.

# app.py import pandas as pd data = {'Show': ['Stranger Things', 'The X-Files', 'Mandalorian', 'The Boys'], 'Streaming': ['Netflix', 'Fx', 'Disney Plus', 'Amazon Prime'], 'Season': [3, 12, 1, 2], 'Main Actor': ['Millie', 'Gillian', 'Padro', 'Karl Urban']} df = pd.DataFrame.from_dict(data) df.drop(columns=['ABC'], errors='ignore') print(df)

python3 app.py Show Streaming Season Main Actor 0 Stranger Things Netflix 3 Millie 1 The X-Files Fx 12 Gillian 2 Mandalorian Disney Plus 1 Padro 3 The Boys Amazon Prime 2 Karl Urban

Pandas DataFrame drop() is a beneficial method to remove unwanted columns and rows. We have seen how to use iloc[] and loc[] with the drop() method.

DataFrame.loc

Returns label-location based indexer for selection by the label.

DataFrame.dropna

Returns DataFrame with labels on given axis omitted, where (all or any) data are missing.

DataFrame.drop_duplicates

Returns DataFrame with duplicate rows removed, optionally only considering specific columns.

The post Pandas Drop Column: How to Drop Column in DataFrame appeared first on AppDividend.

]]>Numpy dot() method returns the dot product of two arrays. For 2D vectors, it is equal to matrix multiplication. For 1D arrays, it is the inner product of the vectors. For N-dimensional arrays, it is the sum-product over the last axis of a and the second-last axis of b. Numpy dot() Numpy dot() is a […]

The post Numpy dot Example | np dot() in Python appeared first on AppDividend.

]]>Numpy dot() method returns the dot product of two arrays. For 2D vectors, it is equal to matrix multiplication. For 1D arrays, it is the inner product of the vectors. For N-dimensional arrays, it is the sum-product over the last axis of **a** and the second-last axis of **b**.

Numpy dot() is a mathematical function that is used to return the mathematical dot of two given vectors (lists). The vectors can be single dimensional as well as multidimensional. In both cases, it follows the rule of the mathematical dot product.

numpy.dot(vector_a, vector_b, out = None)

The dot() function takes mainly three parameters:

**vector_a**: This is the first vector.**vector_b**: This is the second vector.**out**: Argument Production. This must have the same sort that would be returned unless it was used. Specifically, it must have the appropriate form, must be C-contiguous, and its dtype must be the form returned for dot(a, b). That is a feature of the performance. Therefore, if those conditions are not met, instead of attempting to be flexible, an exception is made.

The numpy.dot() method returns the dot product of two given vectors. If any of the vectors or both the vectors are complex, then it’s complex conjugate is used to calculate the dot product.

See the following code.

# Program to show working of numpy.dot # When both the vectors are 1D # Importing numpy import numpy as np # We will create an 1D array arr1 = np.array([1, 2, 3, 4]) arr2 = np.array([2, 3, 4, 5]) # Printing the array print("The first array is: ", arr1) print("The second array is: ", arr2) # Shape of the array print("Shape of the first array is : ", np.shape(arr1)) print("Shape of the second array is : ", np.shape(arr2)) # Printing dot product of the arr1.arr2 out = np.dot(arr1, arr2) print("Dot product of arr1 and arr2") print(out) # When both are complex a = 6+1j b = 4+3j out1 = np.dot(a, b) print("Dot product of a and b") print(out1)

The first array is: [1 2 3 4] The second array is: [2 3 4 5] Shape of the first array is : (4,) Shape of the second array is : (4,) Dot product of arr1 and arr2 40 Dot product of a and b (21+22j)

In this program, in the first case, we have initialized two 1D arrays, and then we have printed both the arrays and their shape also. After that, we have called numpy.dot() to calculate the dot product of the arrays.

We can see that we got the answer 40. According to the rule of the dot product, it did like this way

*(1*2+2*3+3*4+4*5) = 40.*

Also, in the second case, we have declared two complex equations. Then we printed dot products of them. We can see that the answer is (21+22j), which was calculated in this way:

6*(4+3j) + 1j*(4-3j)

= 24+18j+4j-3

= 21+22j

See the following code.

# Program to show the working of numpy.dot # When both the vectors are 2D # Importing numpy import numpy as np # We will create an 1D array arr1 = np.array([[1, 2], [5, 6]]) arr2 = np.array([[2, 3], [2, 4]]) # Printing the array print("The first array is:\n ", arr1) print("\nThe second array is: \n ", arr2) # Shape of the array print("Shape of the first array is : ", np.shape(arr1)) print("Shape of the second array is : ", np.shape(arr2)) # Printing dot product of the arr1.arr2 out = np.dot(arr1, arr2) print("Dot product of arr1 and arr2") print(out)

The first array is: [[1 2] [5 6]] The second array is: [[2 3] [2 4]] Shape of the first array is : (2, 2) Shape of the second array is : (2, 2) Dot product of arr1 and arr2 [[ 6 11] [22 39]]

In this program, in the first case, we have initialized two 2D arrays, and then we have printed both the arrays and their shape also. After that, we have called numpy.dot() to calculate the dot product of the arrays.

We can see that the answer is in the 2D array. According to the rule of the dot product, we got the answer.

That is it for the Numpy dot() method.

The post Numpy dot Example | np dot() in Python appeared first on AppDividend.

]]>Numpy log10() mathematical function helps the user to calculate the Base-10 logarithm of x where x belongs to all the input array items. Numpy log10 Example Numpy log10() is a mathematical function that is used to get the natural logarithm of any object or an array with the base 10. Syntax numpy.log10(array[, out] = ufunc […]

The post Numpy log10 Example | np log10() Function in Python appeared first on AppDividend.

]]>Numpy log10() mathematical function helps the user to calculate the **Base-10 logarithm of x** where x belongs to all the input array items.

**Numpy log10() is a mathematical function that is used to get the natural logarithm of any object or an array with the base 10.**

numpy.log10(array[, out] = ufunc ‘log10’)

The log10() function can take up to two main arguments:

- array: This is the input array or the object whose log is to be calculated.
- out: This is an optional field. A position the result is stored in. If given, it must have a form to which the inputs convey. If not given or None, it returns a freshly-allocated list. A tuple must have length the same to the number of outputs (possible only as a keyword argument).

The log10() function returns an array of natural logarithms of the elements of the given array elements where the base is 10.

See the following code.

# Program to show the working of numpy.log # Importing numpy import numpy as np # We will create an 1D array arr = np.array([4, 14, 10, 63, 11, 4, 64]) # Printing the array print("The array is: ", arr) # Shape of the array print("Shape of the array is : ", np.shape(arr)) # Calculating natural log of value arr[i]+1 out = np.log10(arr) print("Natural logarithm of the given array of base 10 is ") print(out)

The array is: [ 4 14 10 63 11 4 64] Shape of the array is : (7,) Natural logarithm of the given array of base 10 is [0.60205999 1.14612804 1. 1.79934055 1.04139269 0.60205999 1.80617997]

In this program, we have first declared an array of shape 7, and then we have printed the array. Then we have called numpy.log10() to calculate the natural logarithm of the items of the given array.

Let’s see the graphical representation of the log10() function.

# Program to show Graphical representation # Importing numpy import numpy as np import matplotlib.pyplot as plt # We will create an 1D array arr = np.array([40, 2.4, 0.14, 63, 1.2, 1, 4]) # Printing the array print("The array is: ", arr) # Shape of the array print("Shape of the array is : ", np.shape(arr)) # Calculating natural log of value arr[i]+1 out = np.log10(arr) print("Natural logarithm of the given array of base 10 is ") print(out) # Ploting of original array in Graph # Color will be in Green plt.plot(arr, arr, color='green', marker='x') # Ploting of natural log array in Graph # Color will be in blue plt.plot(out, arr, color='blue', marker='o') # Showing the Graphical represntation plt.title("numpy.log10()") plt.xlabel("Natural Log Array") plt.ylabel("Original Array") plt.show()

The array is: [40. 2.4 0.14 63. 1.2 1. 4. ] Shape of the array is : (7,) Natural logarithm of the given array of base 10 is [ 1.60205999 0.38021124 -0.85387196 1.79934055 0.07918125 0. 0.60205999]

In this program, we have first declared an array of shape 7, and then we have printed the array where array elements are in float data type.

Then we have called numpy.log10() to calculate the natural logarithm of the elements of the given array.

After that, we have plotted the original array in a 2D graph which indicates using the Greenline.

Then we have plotted the out array, which we got after finding the natural logarithm, and this indicates using the blue line.

We can see the result in the above-given image.

That is it for the numpy log10() method.

The post Numpy log10 Example | np log10() Function in Python appeared first on AppDividend.

]]>Numpy log2() is a mathematical function that is used to get the natural logarithm of any object or an array. In this case, we have a base of 2 when we find the logarithm of the array. Numpy log2() Numpy log2() is a mathematical function that helps the user to calculate Base-2 logarithm of x where […]

The post Numpy log2() Method Example in Python appeared first on AppDividend.

]]>**Numpy log2() is a mathematical function that is used to get the natural logarithm of any object or an array. **In this case, we have a base of *2* when we find the logarithm of the array.

Numpy log2() is a mathematical function that helps the user to calculate **Base-2 logarithm of x** where x belongs to all the input array elements.

numpy.log2(array[, out] = ufunc ‘log2’)

The log2() function can take up to two main arguments:

- array: This is the input array or the object whose log is to be calculated.
- out: This is an optional field. A position the result is stored in. If given, it must have a form to which the inputs convey. If not given or None, it returns a freshly-allocated list. A tuple must have length the same to the number of outputs (possible only as a keyword argument).

The log2() function returns an array of natural logarithms of the elements of the given array elements where the base is 2.

See the following code.

# Program to show working of numpy.log # Importing numpy import numpy as np # We will create an 1D array arr = np.array([4, 14, 10, 63, 11, 4, 64]) # Printing the array print("The array is: ", arr) # Shape of the array print("Shape of the array is : ", np.shape(arr)) # Calculating natural log of value arr[i]+1 out = np.log2(arr) print("Natural logarithm of the given array of base 2 is ") print(out)

The array is: [ 4 14 10 63 11 4 64] Shape of the array is : (7,) Natural logarithm of the given array of base 2 is [2. 3.80735492 3.32192809 5.97727992 3.45943162 2. 6. ]

In this program, we have first declared an array of shape 7, and then we have printed the array. Then we have called numpy.log2() to calculate the natural logarithm of the elements of the given array.

See the following code.

# Program to show Graphical representation # Importing numpy import numpy as np import matplotlib.pyplot as plt # We will create an 1D array arr = np.array([40, 2.4, 14, 63, 1.2, 1, 4]) # Printing the array print("The array is: ", arr) # Shape of the array print("Shape of the array is : ", np.shape(arr)) # Calculating natural log of value arr[i]+1 out = np.log2(arr) print("Natural logarithm of the given array of base 2 is ") print(out) # Ploting of original array in Graph # Color will be in Green plt.plot(arr, arr, color='green', marker='x') # Ploting of natural log array in Graph # Color will be in blue plt.plot(out, arr, color='blue', marker='o') # Showing the Graphical represntation plt.title("numpy.log2()") plt.xlabel("Natural Log Array") plt.ylabel("Original Array") plt.show()

The array is: [40. 2.4 14. 63. 1.2 1. 4. ] Shape of the array is : (7,) Natural logarithm of the given array of base 2 is [5.32192809 1.26303441 3.80735492 5.97727992 0.26303441 0. 2. ]

In this program, we have first declared an array of shape 7, and then we have printed the array where array elements are in float data type. Then we have called numpy.log2() to calculate the natural logarithm of the elements of the given array.

After that, we have plotted the original array in a 2D graph which indicates using the Greenline. Then we have plotted the out array which we got after finding the natural logarithm, and this shows using the blue line.

We can see the result in the above-given image.

That is it for the Numpy log2() function example.

The post Numpy log2() Method Example in Python appeared first on AppDividend.

]]>Numpy log1p() is a mathematical function that helps the user to calculate the natural logarithmic value of x+1 where x belongs to all the input array elements. log1p is reverse of exp(x) – 1. Numpy log1p() Numpy log() function is used to get the natural logarithm of value x+1, where x is an element of an […]

The post Numpy log1p Example | np log1p() in Python appeared first on AppDividend.

]]>Numpy log1p() is a mathematical function that helps the user to calculate the natural logarithmic value of x+1 where x belongs to all the input array elements. **log1p** is reverse of **exp(x) – 1**.

**Numpy log() function is used to get the natural logarithm of value x+1, where x is an element of an array or x is an object. **The log1p is the reverse of exp(x) – 1.

numpy.log1p(array[, out] = ufunc ‘log1p’)

The np log1p() function can take up to two main arguments:

- array: This is the input array or the object whose log is to be calculated. But the function will add 1 with all elements of the array.

- out: This is an optional field. A position the result is stored in. If the given, it must have the form to which the inputs convey. If not given or None, it returns a freshly-allocated list. A tuple must have length the same to the number of outputs (possible only as a keyword argument).

The log1p() function returns an array of natural logarithms of value x+1 of the elements of the given array elements.

See the following code.

# Program to show the working of numpy.log # Importing numpy import numpy as np # We will create an 1D array arr = np.array([4, 14, 10, 63, 11, 4, 64]) # Printing the array print("The array is: ", arr) # Shape of the array print("Shape of the array is : ", np.shape(arr)) # Calculating natural log of value arr[i]+1 out = np.log1p(arr) print("Natural logarithm of the given array is ") print(out)

The array is: [ 4 14 10 63 11 4 64] Shape of the array is : (7,) Natural logarithm of the given array is [1.60943791 2.7080502 2.39789527 4.15888308 2.48490665 1.60943791 4.17438727]

In this program, we declared an array of shape 7, and then we have printed the array. Then we have called numpy.log1p() to calculate the natural logarithm of value arr[i]+1 of the elements of the given array.

See the following code.

# Program to show Graphical represntation # Importing numpy import numpy as np import matplotlib.pyplot as plt # We will create an 1D array arr = np.array([40, 2.4, 0.14, 63, 1.2, 1, 4]) # Printing the array print("The array is: ", arr) # Shape of the array print("Shape of the array is : ", np.shape(arr)) # Calculating natural log of value arr[i]+1 out = np.log1p(arr) print("Natural logarithm of the given array is ") print(out) # Ploting of original array in Graph # Color will be in Green plt.plot(arr, arr, color='green', marker='x') # Ploting of natural log array in Graph # Color will be in blue plt.plot(out, arr, color='blue', marker='o') # Showing the Graphical represntation plt.title("numpy.log1p()") plt.xlabel("Natural Log Array") plt.ylabel("Original Array") plt.show()

The array is: [40. 2.4 0.14 63. 1.2 1. 4. ] Shape of the array is : (7,) Natural logarithm of the given array is [3.71357207 1.22377543 0.13102826 4.15888308 0.78845736 0.69314718 1.60943791]

In this program, we have first declared an array of shape 7, and then we have printed the array where array elements are in float data type. Then we have called numpy.log1p() to calculate the natural logarithm of the elements of the given array.

After that, we have plotted the original array in a 2D graph which indicates using the Greenline. Then we have plotted the out array which we got after finding the natural logarithm, and this shows using the blue line. We can see the result in the above-given image.

That is it for the numpy log1p() method example.

The post Numpy log1p Example | np log1p() in Python appeared first on AppDividend.

]]>Numpy linalg matrix_rank() method is used to calculate the Matrix rank of a given matrix using the SVD method. The matrix rank is calculated by the number of singular values of the Matrix that are greater than tol. Numpy linalg matrix_rank() The matrix_rank() function returns the matrix rank of an array using the SVD method. […]

The post Numpy linalg matrix_rank() Function Example appeared first on AppDividend.

]]>Numpy linalg matrix_rank() method is used to calculate the Matrix rank of a given matrix using the SVD method. The matrix rank is calculated by the number of singular values of the Matrix that are greater than **tol***.*

The matrix_rank() function returns the matrix rank of an array using the SVD method.

numpy.linalg.matrix_rank(array, tol)

The matrix_rank() function takes mainly two parameters:

**Array**: This is the array whose rank we want to find.**tol**: Threshold below which SVD values are considered zero. If*tol*is None, and S is an array with singular values for*M*, and eps is the epsilon value for datatype of S, then*tol*is set to S.max() * max(M.shape) * eps.

The default limit for detecting rank errors is m. K is a test on the magnitude of the single values. By default, we found smasher values lower than s.max () * max (mHap) * EPS. .

This default range is designed to detect rank reduction accounting for numerical errors of SVD calculation. Hold a column M in M, which is the exact combination (floating point) of the other columns in M. Calculating SVD on M usually does not produce a single value equal to 0: the smallest SVD value.

Any difference from 0 due to numerical disturbances in SVD calculation. Our range for small SVD values takes this numerical disturbance into account, and the default threshold recognizes the absence of such numeric rank.

Although the linear combination of some columns of M is not equal to the second column of M, although numerically very close to the second column of M, the entry matrix M can declare a decrease in rank.

We chose our default limit because it is in widespread use. Other limitations are possible. For example, the 2007 version of the consonant consonant has the optional array smacks () * np.info (M.dtype) elsewhere .eps / 2. * np.sqrt (m + n + 1.). The authors describe this limitation based on the “round off error”.

SVD calculations have the above limitations to deal with the floating-point roundoff error. However, you may have more information about the origins of the error in M, which takes into account other tolerance values to determine the effective rank error.

The most useful measure of patience depends on the functions you want to use on your Matrix. For example, if your data comes from uncertain measurements with greater uncertainty than the floating-point Epsilon, it is better to choose a tolerance close to that uncertainty. Patience is perfect if uncertainty is absolute rather than relative.

The matrix_rank() function returns an integer value, which denotes the rank of the given Matrix.

See the following code.

# Programming example to find matrix rank of the 1D matrix from numpy import linalg as LA import numpy as np arr1 = np.array([4, 5, 0, 1]) print("Matrix rank of the 1st array is: ", LA.matrix_rank(arr1, 0)) arr2 = np.array(np.zeros(4)) print("The Matrix is: ", arr2) print("Matrix rank of the 2nd array is: ", LA.matrix_rank(arr2, 0))

Matrix rank of the 1st array is: 1 The Matrix is: [0. 0. 0. 0.] Matrix rank of the 2nd array is: 0

In this program, we have first imported numpy and numpy.linalg to compute the matrix rank.

We have declared two 1D arrays, and then we had passed tol value when we called matrix_rank() function. We got matrix rank according to the value given.

See the following code.

# Programming example to find matrix rank of 3D matrix from numpy import linalg as LA import numpy as np arr1 = np.array([[1, 2, 3], [6, 5, 4]]) print("The arr1 is :\n", arr1) print("Matrix Rank is:\n", LA.matrix_rank(arr1, 1)) arr2 = np.array(np.zeros((4, 4))) print("Arr2 is: \n: ", arr2) print("Matrix Rank is:\n", LA.matrix_rank(arr2, 2))

The arr1 is : [[1 2 3] [6 5 4]] Matrix Rank is: 2 Arr2 is: : [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] Matrix Rank is: 0

In this program, we have first imported numpy and numpy.linalg to compute the matrix rank.

We have declared two 2D arrays, and then we had passed tol value when we called matrix_rank() function. We got matrix rank according to the value passed.

That is it for the numpy linalg matrix_rank() method.

The post Numpy linalg matrix_rank() Function Example appeared first on AppDividend.

]]>How is tensordot calculated? Numpy tensordot() is used to calculate the tensor dot product of two given tensors. If we have given two tensors a and b, and two arrays like objects which denote axes, let say a_axes and b_axes. The tensordot() function sum the product of a’s elements and b’s elements over the axes […]

The post Numpy tensordot() Function Example in Python appeared first on AppDividend.

]]>Numpy tensordot() is used to calculate the tensor dot product of two given tensors.

If we have given two tensors a and b, and two arrays like objects which denote axes, let say a_axes and b_axes.

The tensordot() function sum the product of a’s elements and b’s elements over the axes specified by a_axes and b_axes.

These a_axes and b_axes can be a scaler too, let say N. In this case, the last N dimension of the given tensors is summed over.

The tensordot() function calculates the tensor dot product along specified axes.

Given two tensors, a and b, and an array_like object containing two array_like objects, (a_axes, b_axes), sum the products of a’s and b’s elements (components) over the axes specified by a_axes and b_axes.

The third argument can be a single non-negative integer_like scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over.

numpy.tensordot(tensor1, tensor2, axes)

The tensordot() function takes three main arguments:

**tensor1: This is an array-like object.****tensor2**: This is also an array-like object. We will calculate tensordot of tensor1 and tensor2.**axes**: This can be a scalar as well as an array-like object. This indicates the axes on which we have to find tensordot.

The tensordot() function returns the tensordot product of the given tensors.

See the following code.

# Programming example of tensordot when axes is array-like object import numpy as np # Declaring arrays arr1 = np.arange(8).reshape(4, 2) arr2 = np.arange(4, 12).reshape(2, 4) print("Tensor1 is: ", arr1) print("\nTensor2 is: ", arr2) # Now we will calculate tensor dot ans = np.tensordot(arr1, arr2, axes=([1, 0], [0, 1])) print("Tensordot of these tensors is:\n", ans)

Tensor1 is: [[0 1] [2 3] [4 5] [6 7]] Tensor2 is: [[ 4 5 6 7] [ 8 9 10 11]] Tensordot of these tensors is: 238

In this programming example, we have first declared two tensors and printed them in the output. Then we have called tensordot() function to calculate the tensordot of these two given tensors. In this case, our given axes are an array-like object.

See the following code.

# Programming example of tensordot when axes is an scalar import numpy as np # Declaring arrays arr1 = np.arange(8).reshape(4, 2) arr2 = np.arange(4, 12).reshape(2, 4) print("Tensor1 is: ", arr1) print("\nTensor2 is: ", arr2) # Now we will calculate tensor dot ans = np.tensordot(arr1, arr2, axes=1) print("Tensordot of these tensors is:\n", ans)

Tensor1 is: [[0 1] [2 3] [4 5] [6 7]] Tensor2 is: [[ 4 5 6 7] [ 8 9 10 11]] Tensordot of these tensors is: [[ 8 9 10 11] [ 32 37 42 47] [ 56 65 74 83] [ 80 93 106 119]]

In this programming example, we have first declared two tensors and printed them in the output. Then we have called tensordot() function to calculate the **tensordot** of these two given tensors. In this case, our given axes are a scalar value.

The idea with tensordot is pretty simple – We input the arrays and the respective axes along which the sum-reductions are intended.

The axes that take part in sum-reduction are removed in the output, and all of the remaining axes from the input arrays are spread-out as different axes in the output, keeping the order in which the input arrays are fed.

Finally, the Numpy tensordot() Function Example is over.

The post Numpy tensordot() Function Example in Python appeared first on AppDividend.

]]>Numpy linalg cond() function computes the condition number of a matrix. The cond() function is capable of returning the condition number using one of seven different norms, depending on the value of p. Numpy linalg cond() Numpy linalg cond() is used to find the condition number of the matrix. The linalg cond() function returns the […]

The post Numpy linalg cond() Function Example appeared first on AppDividend.

]]>Numpy linalg cond() function computes the condition number of a matrix. The cond() function is capable of returning the condition number using one of seven different norms, depending on the value of p.

**Numpy linalg cond() is used to find the condition number of the matrix. The linalg cond() function returns the condition number using one of the 7 norms and the return value depends upon the given value below:**

- None: 2-norm, computed directly using the SVD
- ‘fro’: Frobenius norm
- Inf: max(sum(abs(x), axis=1))
- -inf: min(sum(abs(x+), axis=1))
- 1: max(sum(abs(x), axis=0))
- -1: min(sum(abs(x), axis=0))
- 2: 2-norm (largest sign value)
- -2: smallest singular value

numpy.linalg.cond ( array, condition_value)

The linalg cond() function takes two main arguments:

**array: The array whose condition number we have to find.****condition_value**: This value is one of the 8 values given above.

The linalg cond() function returns the condition number ( float type ).

See the following code.

# Programming example of linalg.cond from numpy import linalg as LA import numpy as np arr = np.array([[2, 0, 2], [3, 1, 0], [1, 0, 1]]) print("The array is:\n", arr) # Finding the cond of the array print(LA.cond(arr)) # When cond='fro' print(LA.cond(arr, 'fro')) # When cond=infinite print(LA.cond(arr, np.inf)) print(LA.cond(arr, -np.inf)) # When cond = 1,2 print(LA.cond(arr, 1)) print(LA.cond(arr, 2))

The array is: [[2 0 2] [3 1 0] [1 0 1]] 1.1866952516534238e+17 inf inf inf inf 1.1866952516534238e+17

In this program, we have first declared the numpy array of size 3×3, and we have printed it.

Then we have called **linalg.cond(),** which we have imported as LA from the **numpy** library. We can see that we got different output for different conditions.

This output depends on the given array and the given condition.

Finally, the Numpy linalg cond() function example.

The post Numpy linalg cond() Function Example appeared first on AppDividend.

]]>