Last modified: Dec 02, 2024 By Alexander Williams

Python Pandas columns: Manage DataFrame Columns

The columns attribute in Pandas helps you access and manipulate the column labels of a DataFrame. It's a handy feature for effective data management.

What Is the columns Attribute?

The columns attribute returns the column names of a DataFrame as a Pandas Index object. You can also use it to rename or reassign columns.

Syntax of columns


DataFrame.columns

It’s an attribute, so parentheses aren’t needed.

Installing Pandas

If Pandas isn’t installed, set it up first. Refer to How to Install Pandas in Python.


pip install pandas

Accessing Columns


import pandas as pd

# Create a DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

df = pd.DataFrame(data)

# Get column names
print(df.columns)

Output:


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

The output lists all column labels.

Renaming Columns

You can rename columns by directly assigning a list of new names:


# Rename columns
df.columns = ['First Name', 'Age (Years)', 'City Name']
print(df.columns)

Output:


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

Key Applications

Use columns for:

  • Inspecting column names in large DataFrames.
  • Renaming columns for better readability.
  • Programmatically altering column names based on logic.

Conclusion

The Pandas columns attribute is crucial for DataFrame management. Mastering it will simplify tasks involving data cleaning, transformation, and validation.