w3resource

Pandas Data Series: Calculate the frequency counts of each unique value of a given series

Pandas: Data Series Exercise-19 with Solution

Write a Pandas program to calculate the frequency counts of each unique value of a given series.

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
num_series = pd.Series(np.take(list('0123456789'), np.random.randint(10, size=40)))
print("Original Series:")
print(num_series)
print("Frequency of each unique value of the said series.")
result = num_series.value_counts()
print(result)

Sample Output:

Original Series:
0     1
1     7
2     1
3     6
4     9
5     1
6     0
7     0
8     7
9     9
10    6
11    0
12    1
13    6
14    7
15    0
16    2
17    9
18    2
19    0
20    5
21    2
22    3
23    2
24    3
25    0
26    0
27    8
28    8
29    2
30    9
31    1
32    2
33    9
34    2
35    9
36    0
37    0
38    4
39    8
dtype: object
Frequency of each unique value of the said series.
0    9
2    7
9    6
1    5
6    3
8    3
7    3
3    2
4    1
5    1
dtype: int64         

Explanation:

num_series = pd.Series(np.take(list('0123456789'), np.random.randint(10, size=40)))

  • This line generates a Pandas Series object 'num_series' containing 40 random characters from the list of digits '0123456789'.
  • The characters are selected randomly using the np.random.randint() function with a range of 10, indicating that 10 is the highest integer that can be returned.
  • The np.take() function is then used to select the characters from the list of digits based on the randomly generated indices.

result = num_series.value_counts(): This line creates a new Pandas Series object 'result' by counting the frequency of each unique character in the original Pandas Series object 'num_series' using the .value_counts() method. The resulting Series object 'result' will have the unique characters from the original Series object 'num_series' as its index and the count of each unique character as its value.

The output of print(result) will depend on the random characters generated by the NumPy function np.take().

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to compute the minimum, 25th percentile, median, 75th, and maximum of a given series.
Next: Write a Pandas program to display most frequent value in a given series and replace everything else as 'Other' in the series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/pandas/python-pandas-data-series-exercise-19.php