Coding Ref

How to create a freqeuncy table in Pandas

How to create a freqeuncy table in Pandas

To create a frequency table in Pandas, you can use the value_counts() method on a Pandas Series. This will return a Series containing the counts of each unique value in the original Series.

Here is an example:

main.py
import pandas as pd

# Create a sample Pandas Series
s = pd.Series(['apple', 'orange', 'apple', 'banana'])

# Use the value_counts() method to create a frequency table
freq_table = s.value_counts()

# Print the frequency table
print(freq_table)

This will output the following frequency table:

output
apple     2
banana    1
orange    1
dtype: int64

Create a frequency table for two or more columns

You can also use the crosstab() method to create a frequency table for two or more columns in a Pandas DataFrame.

This can be useful when you want to see the relationship between different variables in your data.

Here is an example:

main.py
import pandas as pd

# Create a sample Pandas DataFrame
df = pd.DataFrame({'fruit': ['apple', 'orange', 'apple', 'banana'],
                   'color': ['red', 'orange', 'green', 'yellow']})

# Use the crosstab() method to create a frequency table
freq_table = pd.crosstab(df['fruit'], df['color'])

# Print the frequency table
print(freq_table)

This will output the following frequency table:

output
color   green  orange  red  yellow
fruit
apple       1       0    1       0
banana      0       0    0       1
orange      0       1    0       0

In both of these examples, the frequency table shows the number of times each unique value appears in the original data.

You'll also like

Related tutorials curated for you

    How to give multiple conditions in loc() in Pandas

    What is categorical data in Pandas?

    How to concatenate in Pandas

    How to filter a Pandas DataFrame

    How to drop duplicate rows in Pandas

    What is date_range() in Pandas?

    What is Pandas Cumsum()?

    What does Count() do in Pandas?

    How to convert a series to a list in Pandas

    How to change the order of columns in Pandas

    How to drop an index column in Pandas

    How to create a freqeuncy table in Pandas