Create List of Column Names Based On Type in Python (Example Code)

In this tutorial you’ll learn how to return a list of column names grouped by the type of the column in Python programming.

Setting up the Example

import pandas as pd                               # Import pandas library to Python
my_df = pd.DataFrame({'A':[3, 6, 2, 5, 1, 9],    # Construct example DataFrame
                      'B':['g', 'g', 'w', 'a', 'g', 'f'],
                      'C':['a', 'b', 'c', 'd', 'e', 'f'],
                      'D':range(1, 7)})
print(my_df)                                     # Display example DataFrame in console
#    A  B  C  D
# 0  3  g  a  1
# 1  6  g  b  2
# 2  2  w  c  3
# 3  5  a  d  4
# 4  1  g  e  5
# 5  9  f  f  6

Example: Grouping Column Names by Types

print(my_df.columns.to_series().groupby(my_df.dtypes).groups)
# {int64: ['A', 'D'], object: ['B', 'C']}

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top