You may use the following syntax to check the data type of all columns in Pandas DataFrame:
df.dtypes
Alternatively, you may use the syntax below to check the data type of a particular column in Pandas DataFrame:
df['DataFrame Column'].dtypes
Steps to Check the Data Type in Pandas DataFrame
Step 1: Gather the Data for the DataFrame
To start, gather the data for your DataFrame.
For illustration purposes, let’s use the following data about products and prices:
Products | Prices |
AAA | 200 |
BBB | 700 |
CCC | 400 |
DDD | 1200 |
EEE | 900 |
The goal is to check the data type of the above columns across multiple scenarios.
Step 2: Create the DataFrame
Next, create the actual DataFrame based on the following syntax:
import pandas as pd Data = {'Products': ['AAA','BBB','CCC','DDD','EEE'], 'Prices': ['200','700','400','1200','900']} df = pd.DataFrame(Data) print (df)
Once you run the code in Python, you’ll get this DataFrame:
Note that initially the values under the ‘Prices’ column were stored as strings by placing quotes around those values.
Step 3: Check the Data Type
You can now check the data type of all columns in the DataFrame by adding df.dtypes to the code:
df.dtypes
Here is the complete Python code for our example:
import pandas as pd Data = {'Products': ['AAA','BBB','CCC','DDD','EEE'], 'Prices': ['200','700','400','1200','900']} df = pd.DataFrame(Data) print (df.dtypes)
You’ll notice that the data type for both columns is ‘Object‘ which represents strings:
Let’s now remove the quotes for all the values under the ‘Prices’ column:
import pandas as pd Data = {'Products': ['AAA','BBB','CCC','DDD','EEE'], 'Prices': [200,700,400,1200,900]} df = pd.DataFrame(Data) print (df.dtypes)
After the removal of the quotes, the data type for the ‘Prices’ column would become integer:
Checking the Data Type of a Particular Column in Pandas DataFrame
Let’s now check the data type of a particular column (e.g., the ‘Prices’ column) in our DataFrame:
df['DataFrame Column'].dtypes
Here is the full syntax for our example:
import pandas as pd Data = {'Products': ['AAA','BBB','CCC','DDD','EEE'], 'Prices': [200,700,400,1200,900]} df = pd.DataFrame(Data) print (df['Prices'].dtypes)
The data type for the ‘Prices’ column would be integer:
But what if you want to convert the data type from integer to float?
You may then apply this template to perform the conversion:
df['DataFrame Column'] = df['DataFrame Column'].astype(float)
For instance, let’s convert the ‘Prices’ column from integer to float:
import pandas as pd Data = {'Products': ['AAA','BBB','CCC','DDD','EEE'], 'Prices': [200,700,400,1200,900]} df = pd.DataFrame(Data) df['Prices'] = df['Prices'].astype(float) print (df['Prices'].dtypes)
Once you run the code, you’ll notice that the data type for the ‘Prices’ column is now float:
You may wish to check the Pandas Documentation for additional information about df.dtypes.