Do you want to get a list of all the column headers from a Pandas DataFrame? It’s easy to do!
Let’s begin!
Contents
Get a List of Column Headers from a Pandas DataFrame
Just follow these simple steps:
- Import the Pandas library
- Create a DataFrame object
- Use the list() function to get a list of all the column headers from the DataFrame object
Here’s an example of how to do it:
#python with wholeblogs import pandas as pd df = pd.DataFrame({'col_one': [0,0,0], 'col_two': [0, 0, 0], 'col_three': [0, 0, 0]}) print(list(df))
Output
[‘col_one’, ‘col_two’, ‘col_three’]
list() function is not limited to just column headers. You can use it on DataFrame objects too! Try it out and see what you get. list(df) will return a list of all the values in the DataFrame, including the column headers.
list(df[‘col_one’]) will return a list of all the values in that column. Give it a go! See how easy it is to get lists from Pandas DataFrames? It’s a handy skill to have in your toolkit. Happy coding!
Conclusion
That’s all there is to it! Getting a list of column headers from a Pandas DataFrame is easy using the list() function. Give it a try yourself and see how simple it is.
Happy coding!
Read More: How to drop multiple columns in pandas
Pandas read_csv no header set column names
If you want to read in a csv file without the header row, you can use the following code:
import pandas as pd df = pd.read_csv("file.csv", skiprows=1) print(df)