Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (19k points)

I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I don't know how many columns there will be or what they will be called.

For example, if I'm given a DataFrame like this:

>>> my_dataframe

   y gdp cap

0 1  2 5

1 2  3 9

2 8  7 2

3 3  4 7

4 6  7 7

5 4  8 3

6 8  2 8

7 9  9 10

8 6  6 4

9 10 10 7

I would want to get a list like this:

>>> header_list ['y', 'gdp', 'cap']

2 Answers

0 votes
by (33.1k points)

If the name of your DataFrame is my_dataframe. You can get the values as a list by doing:

# Import pandas package 

import pandas as pd 

# making data frame 

my_dataframe= pd.read_csv("nba.csv") 

list(my_dataframe.columns.values) 

Also, you can simply use:

list(my_dataframe)

0 votes
by (47.6k points)

To get the values as a list you can use the following piece of code:

list(my_dataframe.columns.values)

Another thing  you can use: 

list(my_dataframe)

Both methods will give you the desired output that you want.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...