To get the column names of a pandas DataFrame and create a list in Python, the easiest way by using columns.to_list() on a DataFrame.
import pandas as pd
df = pd.DataFrame({"a":[1],"b":[2],"c":[3],"d":[4]})
columns = df.columns.to_list()
print(columns)
#Output:
["a","b","c","d"]
You can also use the Python list() function to get DataFrame column names as a list.
import pandas as pd
df = pd.DataFrame({"a":[1],"b":[2],"c":[3],"d":[4]})
columns = list(df)
print(columns)
#Output:
["a","b","c","d"]
When working with collections of data, the ability to be able to easily access certain pieces of information is valuable.
One such situation is if you want to get the columns of a pandas DataFrame in Python.
There are a few ways you can convert the columns of a pandas DataFrame to a list.
Having the column names in a list can be useful if you want to loop over the columns and perform an action.
The easiest way is to access the column labels with the pandas DataFrame columns attribute and then use the to_list() function.
Below shows a simple example of how you can get the columns of a DataFrame as a list in Python.
import pandas as pd
df = pd.DataFrame({"a":[1],"b":[2],"c":[3],"d":[4]})
columns = df.columns.to_list()
print(columns)
#Output:
["a","b","c","d"]
Using list() to Get pandas Column Names as List in Python
Another way you can convert columns names to a list is with the Python list() function.
list() tries to convert a Python object to a list. The list representation of a pandas DataFrame is the column names.
Therefore, we can use list() to get the column names as a list.
Below shows another example of how you can get the columns of a DataFrame as a list in Python.
import pandas as pd
df = pd.DataFrame({"a":[1],"b":[2],"c":[3],"d":[4]})
columns = list(df)
print(columns)
#Output:
["a","b","c","d"]
Hopefully this article has been useful for you to be able to learn how to get the column names as a list in Python.