Check Data Type of Columns in pandas DataFrame in Python (2 Examples)
This tutorial illustrates how to get the class of all columns in a pandas DataFrame in Python.
The post will consist of this content:
With that, here’s how to do it:
Example Data & Libraries
In order to use the functions of the pandas library, we first have to load pandas:
import pandas as pd # Import pandas library
As a next step, we’ll also have to create some example pandas DataFrame:
data = pd.DataFrame({'x1':range(60, 55, - 1), # Create pandas DataFrame 'x2':['a', 'b', 'c', 'b', 'c'], 'x3':[True, False, False, True, True]}) print(data) # Print pandas DataFrame
Table 1 illustrates that our example data contains five rows and three variables.
Example 1: Get Data Type of Single Column in pandas DataFrame
This example shows how to return the data class of one single variable of a pandas DataFrame in Python.
For this task, we can use the dtype attribute as shown below:
print(data.x1.dtype) # Print type of one column # int64
As you can see based on the previous output of the console, the column x1 has the data type int64.
Example 2: Get Data Type of All Columns in pandas DataFrame
Example 2 illustrates how to test and print the classes of all columns in a pandas DataFrame.
To achieve this, we can use the dtypes attribute as shown below. Note that we do not have to specify any column names in the following syntax:
print(data.dtypes) # Print type of all columns # x1 int64 # x2 object # x3 bool # dtype: object
The data classes of each column has been printed after executing the previous Python code. The variable x1 has the class int64 (as we already know from Example 1), the variable x2 is an object, and the variable x3 has the bool class.
Video, Further Resources & Summary
I have recently released a video on my YouTube channel, which explains the Python programming syntax of this tutorial. You can find the video below:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may want to have a look at the other articles on my website.
- Introduction to the pandas Library in Python
- Change Data Type of pandas DataFrame Column in Python
- Change Order of Columns in pandas DataFrame in Python
- Add Multiple Columns to pandas DataFrame in Python
- Rename Columns of pandas DataFrame in Python
- Count Rows & Columns of pandas DataFrame in Python
- Check if pandas DataFrame is Empty in Python
- All Python Programming Examples
In summary: At this point you should have learned how to check the type of all columns in a pandas DataFrame in the Python programming language. Tell me about it in the comments, if you have additional comments or questions. Furthermore, don’t forget to subscribe to my email newsletter to get updates on new tutorials.