• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:16 mins read
You are currently viewing Pandas Get Column Names from DataFrame

How to get or print Pandas DataFrame Column Names? You can get the Pandas DataFrame Column Names by using DataFrame.columns.values method and to get it as a list use tolist(). Each column in a Pandas DataFrame has a label/name that specifies what type of value it holds/represents. Getting a column name is useful when you want to access all columns by name programmatically or manipulate the values of all columns. In this article, I will explain different ways to get column names from Pandas DataFrame headers with examples.

To get a list of columns from the DataFrame header use DataFrame.columns.values.tolist() method. Below is an explanation of each section of the statement.

  • .columns returns an Index object with column names. This preserves the order of column names.
  • .columns.values returns an array and this has a helper function .tolist() that returns a list of column names.

1. Quick Examples of Getting Column Names

Following are some quick examples of how to get column names from pandas DataFrame, If you want to print it to the console just use the print() statement.


# Below are some quick examples

# Example 1: Get the list of all column names from headers
column_names = list(df.columns.values)

# Example 2: Get the list of all column names from headers
column_names = df.columns.values.tolist()

# Example 3: Using list(df) to get the column headers as a list
column_names = list(df.columns)

# Example 4: Using list(df) to get the list of all Column Names
column_names = list(df)

# Example 5: Dataframe show all columns sorted list
column_names=sorted(df)

# Example 6: Get all Column Header Labels as List
for column_headers in df.columns: 
    print(column_headers)
    
column_names = df.keys().values.tolist()

# Example 7: Get all numeric columns
numeric_columns = df._get_numeric_data().columns.values.tolist()

# Example 8: Simple Pandas Numeric Columns Code
numeric_columns=df.dtypes[df.dtypes == "int64"].index.values.tolist()

Create a Pandas DataFrame from Dict with a few rows and column names CoursesFeeDuration and Discount.


import pandas as pd
import numpy as np

technologies= {
    'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
    'Fee' :[22000,25000,23000,24000,26000],
    'Duration':['30days','50days','30days', None,np.nan],
    'Discount':[1000,2300,1000,1200,2500]
          }
df = pd.DataFrame(technologies)
print("Create DataFrame:\n", df)

Yields below output.

Pandas get Column names

2. pandas Get Column Names

You can get the column names from pandas DataFrame using df.columns.values, and pass this to the Python list() function to get it as a list, once you have the data you can print it using the print() statement. I will take a moment to explain what is happening in this statement, df.columns attribute returns Index object which is a basic object that stores axis labels. Index object provides a property Index.values that returns data in an array, in our case it returns column names in an array.

Note that df.columns preserve the order of the columns as-is.

To convert an array of column names into a list, we can use either .toList() an array object or use list(array object).

Related: You can also convert the Pandas DataFrame column to Numpy array.


# Get the list of all column names from headers
column_headers = list(df.columns.values)
print("The Column Header :", column_headers)

Yields below output.

Pandas get Column names

You can also use df.columns.values.tolist() to get the DataFrame column names.


# Get the list of all column names from headers
column_headers = df.columns.values.tolist()
print("The Column Header :", column_headers)

3. Use list(df) to Get Column Names from DataFrame

Use list(df) to get the column header from Pandas DataFrame. You can also use a list(df.columns) to get column names.


# Using list(df) to get the column headers as a list
column_headers = list(df.columns)

# Using list(df) to get the list of all Column Names
column_headers = list(df)

4. Get Column Names in Sorting order

In order to get a list of column names in a sorted order use sorted(df) function. This function returns column names in alphabetical order.


# Dataframe show all columns sorted list
col_headers=sorted(df)
print(col_headers)

Yields below output. Notice the difference of output from above.


# Output:
['Courses', 'Discount', 'Duration', 'Fee']

5. Access All Column Names by Iterating

Alternatively, you can get all column names in a DataFrame by iterating through the columns of the DataFrame. You can use a for loop to iterate through the column names, which are obtained using df.columns. The df.columns attribute returns an Index object that contains the names of all the columns of the DataFrame.


# Get all Column Header Labels as List
for column_headers in df.columns: 
    print(column_headers)

Yields below output.


# Output:
Courses
Fee
Duration
Discount

6. Get Column Headers Using the keys() Method

df.keys() is another approach to get all column names as a list from Pandas DataFrame.


# Get column header using keys() method
column_headers = df.keys().values.tolist()
print("The Column Header :", column_headers)

Yields below output.


# Output:
The Column Header : Index(['Courses', 'Fee', 'Duration', 'Discount'], dtype='object')

7. Get All Numeric Column Names

Sometimes while working on the analytics, you may need to work only on numeric columns, hence you would be required to get all columns of a specific data type. For example, getting all columns of numeric data type can be done using an undocumented function df._get_numeric_data().


# Get all numeric columns
numeric_columns = df._get_numeric_data().columns.values.tolist()
print(numeric_columns)

Yields below output.


# Output:
['Fee', 'Discount']

Use for df.dtypes[df.dtypes!="Courses"].index: This is another simple code for finding numeric columns in a pandas DataFrame.


# Simple Pandas Numeric Columns Code
numeric_columns=df.dtypes[df.dtypes == "int64"].index.values.tolist()

Yields the same output as above.

9. Complete Example of pandas Get Columns Names


import pandas as pd
import numpy as np

technologies= {
    'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
    'Fee' :[22000,25000,23000,24000,26000],
    'Duration':['30days','50days','30days', None,np.nan],
    'Discount':[1000,2300,1000,1200,2500]
          }
df = pd.DataFrame(technologies)
print(df)

# Get the list of all column names from headers
column_headers = list(df.columns.values)
print("The Column Header :", column_headers)

# Get the list of all column names from headers
column_headers = df.columns.values.tolist()
print("The Column Header :", column_headers)

# Using list(df) to get the column headers as a list
column_headers = list(df.columns)

# Using list(df) to get the list of all Column Names
column_headers = list(df)

# Dataframe show all columns sorted list
col_headers=sorted(df)
print(col_headers)

# Get all Column Header Labels as List
for column_headers in df.columns: 
    print(column_headers)
    
column_headers = df.keys().values.tolist()
print("The Column Header :", column_headers)

# Get all numeric columns
numeric_columns = df._get_numeric_data().columns.values.tolist()
print(numeric_columns)

# Simple Pandas Numeric Columns Code
numeric_columns=df.dtypes[df.dtypes == "int64"].index.values.tolist()
print(numeric_columns)

Frequently Asked Questions on Get Column Names

How do I get the column names of a DataFrame in Pandas?

You can get the column names of a DataFrame by using the df.columns.values attribute.

How can I get the column names as a list or array?

To get the column names as a list or array, you can convert the df.columns.values attribute to a list using the list() function.

How can I access the column names by index?

You can access column names by their index position using df.columns attributes. For example, to access the name of the first column using this syntax df.columns[0].

How can I extract specific columns by name from a DataFrame?

You can extract specific columns by name by passing a list of column names to the DataFrame. For example, to extract columns "A" and "B", you can use this syntax df[['A', 'B']]

How can I change the order of columns in a DataFrame?

you can change the order of columns in a DataFrame by selecting the columns in the desired order.

Conclusion

In this article, you have learned how to get or print the column names using df.columns, list(df), df.keys, and also learned how to get all column names of type integer, finally getting column names in a sorted order e.t.c

Happy Learning !!

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium

Leave a Reply