To get frequency counts of a column in Pandas, you can use the function of value_counts()
or groupby().size()
. The following shows two actual method examples.
Method 1: df[“column_name”].value_counts()
Method 2: df.groupby([“column_name”]).size()
Data Example
The following is to generate a sample dataframe in Python.
import pandas as pd
car_data = {'Brand': ['Tesla', 'Tesla','Tesla','Ford','Ford','Ford','Toyota','Toyota'],
'Location': ['CA', 'CA','NY','MA','CA','WA','CA','TX'],
'Year':['2019','2018','2020','2019','2016','2010','2018','2021']}
car_data=pd.DataFrame(data=car_data)
# print the dataframe
print(car_data)
The following is the sample dataframe to be used later.
Brand Location Year 0 Tesla CA 2019 1 Tesla CA 2018 2 Tesla NY 2020 3 Ford MA 2019 4 Ford CA 2016 5 Ford WA 2010 6 Toyota CA 2018 7 Toyota TX 2021
Method 1: use value_count()
The first method is to use value_counts()
.
car_data["Brand"].value_counts()
The following is the output showing the frequency counts for each car model for the colum of “Brand.”
Tesla 3 Ford 3 Toyota 2 Name: Brand, dtype: int64
Method 2: use groupby().size()
We can also use the groupby().size() to get the frequency counts for a certain column.
car_data.groupby(["Brand"]).size()
The following is the output.
Brand Ford 3 Tesla 3 Toyota 2 dtype: int64