print all headers from dataframe in python

To print all the headers (column names) from a DataFrame in Python using the pandas library, you can use the columns attribute of the DataFrame.

Here's an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['John', 'Mike', 'Sarah'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}

df = pd.DataFrame(data)

# Print all the headers
print(df.columns)
245 chars
12 lines

Output:

main.py
Index(['Name', 'Age', 'City'], dtype='object')
47 chars
2 lines

In the above code, we create a sample DataFrame and then use the columns attribute to print all the headers.

Note: The columns attribute returns the headers as an Index object. If you want to convert it to a list, you can add .tolist() after df.columns, like this:

main.py
print(df.columns.tolist())
27 chars
2 lines

Output:

main.py
['Name', 'Age', 'City']
24 chars
2 lines

This will give you a list of all the headers in the DataFrame.

related categories

gistlibby LogSnag