0
0
Pandasdata~5 mins

dtypes and data type checking in Pandas

Choose your learning style9 modes available
Introduction

We use dtypes to know what kind of data is stored in each column of a table. This helps us work with data correctly and avoid mistakes.

When you want to see if a column has numbers or words.
Before doing math on data, to make sure the data is numeric.
To check if dates are stored as dates or just text.
When cleaning data, to find columns with wrong data types.
To convert data from one type to another for analysis.
Syntax
Pandas
DataFrame.dtypes

# or for a single column
Series.dtype

dtypes shows the data type of each column in a DataFrame.

For a single column (Series), use dtype to get its type.

Examples
This shows the data type of each column in the DataFrame.
Pandas
import pandas as pd

data = {'age': [25, 30, 22], 'name': ['Alice', 'Bob', 'Carol']}
df = pd.DataFrame(data)
print(df.dtypes)
This shows the data type of the 'age' column only.
Pandas
print(df['age'].dtype)
This shows the data type of the 'name' column only.
Pandas
print(df['name'].dtype)
Sample Program

This program creates a table with numbers, text, booleans, and dates. It then prints the data type of each column and the data type of the 'date' column.

Pandas
import pandas as pd

# Create a DataFrame with different types of data
data = {
    'temperature': [22.5, 23.0, 21.8],
    'city': ['Paris', 'London', 'Berlin'],
    'rain': [False, True, False],
    'date': pd.to_datetime(['2023-06-01', '2023-06-02', '2023-06-03'])
}
df = pd.DataFrame(data)

# Check data types of all columns
print(df.dtypes)

# Check data type of one column
print(df['date'].dtype)
OutputSuccess
Important Notes

In pandas, object usually means text (strings).

Data types help pandas decide what operations can be done on the data.

Use pd.to_datetime() to convert text to date type.

Summary

dtypes tell you the kind of data in each column.

Check dtypes before analysis to avoid errors.

You can check the type of the whole table or just one column.