how to get amount of different classes in pandas df in python

To get the count of different classes in a pandas DataFrame column, you can use the value_counts() function in pandas.

Here is an example code snippet:

main.py
import pandas as pd

# create sample dataframe
df = pd.DataFrame({
    'Class': ['A', 'B', 'C', 'A', 'B', 'A']
})

# count each class
class_counts = df['Class'].value_counts()

print(class_counts)
197 chars
12 lines

Output:

main.py
A    3
B    2
C    1
Name: Class, dtype: int64
47 chars
5 lines

In the above example, we create a sample pandas DataFrame with one column named "Class". We then use the value_counts() function to count the occurrences of each class in the "Class" column, which gives us a pandas Series object with the count of each class.

You can also use normalize=True parameter to get the frequency percentage of each class, as shown below:

main.py
class_counts = df['Class'].value_counts(normalize=True)
56 chars
2 lines

Output:

main.py
A    0.500000
B    0.333333
C    0.166667
Name: Class, dtype: float64
70 chars
5 lines

This will return a pandas Series object with the frequency percentage of each class.

related categories

gistlibby LogSnag