Python Pandas

Pandas Check Column Type

For this one, we will explore how to get the data type of a specific column in a Pandas DataFrame.

Sample

Let us start by creating a sample DataFrame:

# import pandas
import pandas as pd
df = pd.DataFrame({
    'salary': [120000, 100000, 90000, 110000, 120000, 100000, 56000],
    'department': ['game developer', 'database developer', 'front-end developer', 'full-stack developer', 'database developer', 'security researcher', 'cloud-engineer'],
    'rating': [4.3, 4.4, 4.3, 3.3, 4.3, 5.0, 4.4]},
    index=['Alice', 'Michael', 'Joshua', 'Patricia', 'Peter', 'Jeff', 'Ruth'])
print(df)

The above should create a DataFrame with sample data as shown:

Pandas dtype Attribute

The most straightforward way to get the column’s data type in Pandas is to use the dtypes attribute.

The syntax is as shown:

DataFrame.dtypes

The attribute returns each column and its corresponding data type.

An example is as shown:

df.dtypes

The above should return the columns and their data types as shown:

salary          int64
department     object
rating        float64

If you want to get the data type of a specific column, you can pass the column name as an index as shown:

df.dtypes['salary']

This should return the data type of the salary column as shown:

dtype('int64')

Pandas Column Info

Pandas also provide us with the info() method. It allows us to get detailed information about the columns within a Pandas DataFrame.

The syntax is as shown:

DataFrame.info(verbose=None, buf=None, max_cols=None, memory_usage=None, show_counts=None, null_counts=None)

It allows you to fetch the name of the columns, data type, number of non-null elements, etc.

An example is as shown:

df.info()

This should return:

The above shows detailed information about the columns in the DataFrame, including the data type.

Conclusion

This tutorial covers two methods you can use to fetch the data type of a column in a Pandas DataFrame.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list