How to Count the Number of Data Types in a Python Column?

Estimated read time 2 min read

To count the number of data types in a Python column, you can use the value_counts() method of a Pandas dataframe.

Here’s an example:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({
    'column1': [1, 2, 3, 'string1', 'string2', True],
    'column2': ['string3', False, 4.5, 6, 'string4', 'string5']

# count the number of data types in 'column1'
data_type_counts = df['column1'].apply(type).value_counts()


In this example, we create a sample Pandas dataframe with two columns containing values of different data types. To count the number of data types in the 'column1' column, we use the apply() method to apply the type() function to each value in the column. The resulting object will contain the data type of each value in the column. We then use the value_counts() method to count the number of occurrences of each data type.

The output of the example will be:

<class 'str'>      2
<class 'int'>      3
<class 'bool'>     1
Name: column1, dtype: int64

In this output, we can see that the 'column1' column contains 2 strings, 3 integers, and 1 boolean value. Note that the value_counts() method returns a Pandas series object containing the count of each unique value in the column.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply