How to Get Columns of Numeric Datatype from DataFrame?
Pandas DataFrame - Select Columns of Numeric Datatype
To select columns that are only of numeric datatype from a Pandas DataFrame, call DataFrame.select_dtypes() method and pass np.number
or 'number'
as argument for include parameter. The DataFrame.select_dtypes() method for this given argument returns a subset of this DataFrame with only numeric columns.
Syntax of select_datatypes()
The syntax to call select_datatypes() method of a DataFrame is
DataFrame.select_dtypes(include=None, exclude=None)
Examples
1. Select numeric columns from DataFrame
In this example, we have created a DataFrame and we shall get only those columns which are numeric using DataFrame.select_dtypes() method.
Python Program
import pandas as pd
df = pd.DataFrame(
[['abc', 22, 22.6],
['xyz', 25, 23.2],
['pqr', 31, 30.5]],
columns=['name', 'age', 'bmi'])
result = df.select_dtypes(include='number')
print(result)
Output
age bmi
0 22 22.6
1 25 23.2
2 31 30.5
Only the columns with numeric datatype are selected from this DataFrame.
Summary
In this tutorial of Python Examples, we learned how to select only the numeric columns of DataFrame using DataFrame.select_dtypes() method.