How to get column names in Pandas dataframe

How to get column names in Pandas dataframe

To get the column names of a pandas DataFrame, you can simply use the columns attribute. Here's how to do it:

  • First, make sure you have pandas installed:
pip install pandas 
  • Now, create a DataFrame and get its column names:
import pandas as pd # Create a sample DataFrame data = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'San Francisco', 'Los Angeles'] } df = pd.DataFrame(data) # Get column names column_names = df.columns # Print column names print(column_names) 

This will output:

Index(['Name', 'Age', 'City'], dtype='object') 

If you want the column names as a list, you can convert them:

column_names_list = df.columns.tolist() print(column_names_list) 

This will output:

['Name', 'Age', 'City'] 

So, the columns attribute gives you the column names of the DataFrame, and you can easily convert it to a list or other data structures as needed.


More Tags

xcode-ui-testing popover ios jetty pygame-surface progressive-web-apps signals findby absolute geolocation

More Programming Guides

Other Guides

More Programming Examples