Sample
Let us start by creating a sample DataFrame:
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:
The attribute returns each column and its corresponding data type.
An example is as shown:
The above should return the columns and their data types as shown:
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:
This should return the data type of the salary column as shown:
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:
It allows you to fetch the name of the columns, data type, number of non-null elements, etc.
An example is as shown:
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!!