Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count the frequency of a value in a DataFrame column in Pandas
To count the frequency of a value in a DataFrame column in Pandas, we can use df.groupby(column name).size() method.
Steps
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Print frequency of column, x.
Print frequency of column, y.
Print frequency of column, z.
Example
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 5],
"y": [4, 10, 5, 10],
"z": [1, 1, 5, 1]
}
)
print "Input DataFrame is:<br>", df
col = "x"
count = df.groupby('x').size()
print "Frequency of values in column ", col, "is:<br>", count
col = "y"
count = df.groupby('y').size()
print "Frequency of values in column ", col, "is:<br>", count
col = "z"
count = df.groupby('z').size()
print "Frequency of values in column ", col, "is:<br>", count
Output
Input DataFrame is: x y z 0 5 4 1 1 2 10 1 2 1 5 5 3 5 10 1 Frequency of values in column x is: x 1 1 2 1 5 2 dtype: int64 Frequency of values in column y is: y 4 1 5 1 10 2 dtype: int64 Frequency of values in column z is: z 1 3 5 1 dtype: int64
Advertisements
