Skip to main content

Python Pandas Get Column Names (Headers) List With Example

Generating column names list from a dataframe.

Dataframe object has "columns" method which returns the required data object. This can be converted into list. 

Creating a new dataframe with data


# importing pandas
import pandas as pd


# animal_data dictionary
animal_data = {
    "Name": ["Cat", "Dog", "Cow"],
    "Speed": [15, 12, 10],
    "Sound": ["Meow", "Woof", "Mooo"],
}

#creating a dataframe using the animal_data dictionary
animal_df = pd.DataFrame(animal_data)

#printing animal_df
print("animal_df \n", animal_df)
animal_df Name Speed Sound 0 Cat 15 Meow 1 Dog 12 Woof 2 Cow 10 Mooo

# create a list containing values
column_names_as_list = list(animal_df.columns)


print("column_names_as_list \n", column_names_as_list)

print("\n length of column_names_as_list \n", len(column_names_as_list))



#or directly use the values animal_df.columns without converting into list
#for most processing this can be directly used 

column_names = (animal_df.columns)

print("\n column_names \n", column_names)

print("\n length of column_names \n", len(column_names))

column_names_as_list ['Name', 'Speed', 'Sound'] length of column_names_as_list 3 column_names Index(['Name', 'Speed', 'Sound'], dtype='object') length of column_names 3

Comments

Topics

Show more