Can value_counts be used on DataFrames?

The value_counts function is primarily used on Series objects in pandas. However, you can apply it to each column of a DataFrame by using the apply method. Here's an example:

import pandas as pd

# Sample DataFrame
df = pd.DataFrame({
    'A': ['foo', 'bar', 'foo', 'bar', 'foo'],
    'B': [1, 2, 1, 2, 1]
})

# Applying value_counts to each column
value_counts_A = df['A'].value_counts()
value_counts_B = df['B'].value_counts()

print(value_counts_A)
print(value_counts_B)

This will give you the counts of unique values for each specified column in the DataFrame.

0 Comments

no data
Be the first to share your comment!