QBoard » Artificial Intelligence & ML » AI and ML - Python » Get a list from Pandas DataFrame column headers

Get a list from Pandas DataFrame column headers

  • I want to get a list of the column headers from a Pandas DataFrame. The DataFrame will come from user input, so I won'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 get a list like this:
    >>> header_list ['y', 'gdp', 'cap']
      November 2, 2021 7:45 PM IST
    0
  • n = []
    for i in my_dataframe.columns:
        n.append(i)
    print n
      November 29, 2021 11:58 AM IST
    0
  • For a quick, neat, visual check, try this:

    for col in df.columns:
        print col
      November 3, 2021 1:59 PM IST
    0
  • Using list(df) print(list(df)) Output: ['Name', 'Symbol', 'Shares']
    Using df. columns. values. tolist() print(df. columns. values. ...
    Using list comprehension. You can also get the columns as a list using list comprehension. print([col for col in df]) Output: ['Name', 'Symbol', 'Shares']
      November 8, 2021 2:53 PM IST
    0
  • It gets even simpler (by Pandas 0.16.0):
    df.columns.tolist()
    will give you the column names in a nice list.
      November 8, 2021 5:19 PM IST
    0
  • >>> list(my_dataframe)
    ['y', 'gdp', 'cap']

     

    To list the columns of a dataframe while in debugger mode, use a list comprehension:

    >>> [c for c in my_dataframe]
    ['y', 'gdp', 'cap']

     

    By the way, you can get a sorted list simply by using sorted:

    >>> sorted(my_dataframe)
    ['cap', 'gdp', 'y']
      November 9, 2021 2:25 PM IST
    0