Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
data science
data types
dataframe
communitycreator

How to return the datatype of each column of a Dataframe

Onyejiaku Theophilus Chidalu

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 objects
int_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 objects
df = 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 dataframe
a = df.dtypes
print(a)
Return datatypes of each column

Explanation

  • 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.

RELATED TAGS

pandas
data science
data types
dataframe
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring