w3resource

Pandas DataFrame: Get list from DataFrame column headers


22. Getting List from Column Headers

Write a Pandas program to get list from DataFrame column headers.

Sample data:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(list(df.columns.values))

Sample Output:

['attempts', 'name', 'qualify', 'score']                  

Explanation:

The above code defines a dictionary 'exam_data' with keys 'name', 'score', 'attempts', and 'qualify' and their corresponding values as lists. It then defines a list of 'labels' and creates a Pandas DataFrame 'df' from the dictionary with the index set to the list of labels.

print(list(df.columns.values)): This line prints the list of column names in the DataFrame df.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to get a list of all column headers and then convert them to uppercase.
  • Write a Pandas program to extract column names into a list and then sort this list alphabetically.
  • Write a Pandas program to retrieve column headers and then filter the list to only include headers that start with a given letter.
  • Write a Pandas program to get a list of column names and then create a mapping of each column to its data type.

Go to:


Previous: Write a Pandas program to iterate over rows in a DataFrame.
Next: Write a Pandas program to rename columns of a given DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.