We use the attribute pandas.DataFrame.dtype
to return the datatypes of each column of a DataFrame.
DataFrame.dtypes
The DataFrame.dtypes
attribute takes no parameter value.
It returns the data types of each column.
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)
Line 1: We import the pandas
library.
Lines 4–6: We create a list of objects, text_values
, int_values
, and float_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 is df
.
Line 12: We print the dataframe, df
.
Line 14: We obtain the data type of the columns of the dataframe, df
, by calling the DataFrame.dtypes
attribute. The result is assigned to a variable, a
.
Line 15: We print the value of a
containing the column labels of df
.