How to Check the Data Type in a DataFrame
In this tutorial, you will learn how to check the data type of a column in a DataFrame.
TLDR solution
# shows data type for all columns
df.dtypes
# shows data type for one column
df['column'].dtypes
Step-by-Step Example
Suppose, you have the following DataFrame:
import pandas as pd
data = {'date': ['01/15/2021', '02/15/2021', '03/15/2021'],
'fish': ['salmon', 'pufferfish', 'shark'],
'count': [1000, 100, 10.0]
}
df = pd.DataFrame(data)
print(df)
date fish count
0 01/15/2021 salmon 1000
1 02/15/2021 pufferfish 100
2 03/15/2021 shark 10
You can use the dtypes attribute to check the data type of each column in a DataFrame:
print(df.dtypes)
date object
fish object
count float64
dtype: object
Note that the date column is currently of type object/string, and count of type float.
Bonus: Change the Data Type of a Column
Let's convert the type of the date column to datetime and that of count to integer:
df['date'] = pd.to_datetime(df['date'], format='%m/%d/%Y')
df['count'] = df['count'].astype('int')
# check the data type for a subset of columns
print(df[['date', 'count']].dtypes)
date datetime64[ns]
count int64
dtype: object
That's it! You just learned how to check the data types of a DataFrame.