Python Pandas - Return the relative frequency from Index object

PythonServer Side ProgrammingProgramming

To return the relative frequency from Index object, use the index.value_counts() method with parameter normalize as True.

At first, import the required libraries -

import pandas as pd

Creating Pandas index −

index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])

Display the Pandas index −

print("Pandas Index...\n",index)

Get the count of unique values using value_counts(). Set the parameter "normalize" to True to get the relative frequency −

print("\nGet the relative frequency by dividing all values by the sum of values...\n", index.value_counts(normalize=True))

Example

Following is the code −

import pandas as pd

# Creating Pandas index
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Get the count of unique values using value_counts()
# Set the parameter "normalize" to True to get the relative frequency
print("\nGet the relative frequency by dividing all values by the sum of values...\n", index.value_counts(normalize=True))

Output

This will produce the following output −

Pandas Index...
Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64')

Number of elements in the index...
9

The dtype object...
int64

Get the relative frequency by dividing all values by the sum of values...
50    0.222222
110   0.222222
90    0.222222
10    0.111111
70    0.111111
30    0.111111
dtype: float64
raja
Updated on 13-Oct-2021 08:56:37

Advertisements