how to get a name of a column in pandas in python

To get the name of a column in a Pandas DataFrame in Python, you can use the columns attribute of the DataFrame object.

Here is an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['John', 'Adam', 'Emily'],
        'Age': [28, 32, 25],
        'City': ['New York', 'Boston', 'London']}
df = pd.DataFrame(data)

# Get the column names
column_names = df.columns

# Iterate over the column names
for column in column_names:
    print(column)
324 chars
15 lines

This will output:

main.py
Name
Age
City
14 chars
4 lines

In the above example, df.columns returns an Index object containing all the column names of the DataFrame. You can then iterate over this Index object or access a specific column name by its index.

related categories

gistlibby LogSnag