How to return the datatype of each column of a Dataframe
Overview
We use the attribute pandas.DataFrame.dtype to return the datatypes of each column of a DataFrame.
Syntax
DataFrame.dtypes
Syntax for the data types in Pandas
Parameters
The DataFrame.dtypes attribute takes no parameter value.
Return value
It returns the data types of each column.
Example
import pandas as pd# creating a list of objectsint_values = [1, 2, 3, 4, 5]text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']float_values = [0.0, 0.25, 0.5, 0.75, 1.0]# creating a dataframe from the list of objectsdf = pd.DataFrame({"int_column": int_values, "text_column": text_values,"float_col": float_values})print(df)# obtaining the data type of each columns of the dataframea = df.dtypesprint(a)
Explanation
Line 1: We import the
pandaslibrary.Lines 4–6: We create a list of objects,
text_values,int_values, andfloat_values.Line 9: We create a dataframe using the list of objects we created by making use of
pandas.DataFrame(). The name of the dataframe isdf.Line 12: We print the dataframe,
df.Line 14: We obtain the data type of the columns of the dataframe,
df, by calling theDataFrame.dtypesattribute. The result is assigned to a variable,a.Line 15: We print the value of
acontaining the column labels ofdf.