Return List of Variable Names of pandas DataFrame in Python (Example Code)

In this tutorial, I’ll illustrate how to get column names in the Python programming language.

Preparing the Example

import pandas as pd                                 # Import pandas library
my_df = pd.DataFrame({"A":["a", "n", "s", "d"],    # Constructing DataFrame
                      "B":range(11, 15),
                      "C":range(1, 5),
                      "D":["a", "b", "c", "d"],
                      "E":[10, 20, 30, 40]})
print(my_df)                                       # Displaying example data in Python
#    A   B  C  D   E
# 0  a  11  1  a  10
# 1  n  12  2  b  20
# 2  s  13  3  c  30
# 3  d  14  4  d  40

Example: Return List of Column Names in Pythoin

columns_list = list(my_df)                         # Using list() function
print(columns_list)                                # Returning list of variable names
# ['A', 'B', 'C', 'D', 'E']

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