Monday 29 April 2024

How to select only numeric column names in Pandas?

Step 1: Select numeric column names using ‘select_dtypes’ method.

numeric_column_names = df.select_dtypes(include=['float64', 'int64']).columns

 

Step 2: Extract the numeric columns data from dataframe

numeric_data = df[numeric_column_names]

 

Find the below working application.

 

select_only_numeric_columns.py

import pandas as pd

df = pd.DataFrame(
    {
       'a': [1, 2, 3, 4],
        'b': [True, False, True, True],
        'c': [1.23, 4.5, 6.7, 8],
        'd': ['a', 'e', 'i', 'o']
    }
)

numeric_column_names = df.select_dtypes(include=['float64', 'int64']).columns
numeric_data = df[numeric_column_names]

print(f'df : \n{df}')
print(f'\nnumeric_column_names : \n{numeric_column_names}')
print(f'\nnumeric_data : \n{numeric_data}')

 

Output

df : 
   a      b     c  d
0  1   True  1.23  a
1  2  False  4.50  e
2  3   True  6.70  i
3  4   True  8.00  o

numeric_column_names : 
Index(['a', 'c'], dtype='object')

numeric_data : 
   a     c
0  1  1.23
1  2  4.50
2  3  6.70
3  4  8.00

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment