.columns
Published May 12, 2024
Contribute to Docs
The .columns
attribute represents the column labels of the DataFrame. It returns an Index
object and can be used to view or assign new values to the column labels.
Syntax
pandas.DataFrame.columns
Example
In the following example, the .columns
attribute is used to view and modify the column labels of the studentGrades
DataFrame:
import pandas as pd# Creating the DataFrame representing student gradesdata = {'Math': [88, 92, 79, 85],'Science': [94, 77, 90, 78],'English': [89, 80, 95, 81]}studentGrades = pd.DataFrame(data)# Print the column label of the studentGradesprint(studentGrades.columns)# Print the studentGrades DataFrameprint(f'{studentGrades} \n')# modify the column labelstudentGrades.columns = ['Algebra', 'Biology', 'Literature']# print the modified column labelprint(studentGrades.columns)# print the modified studentGrades Dataframeprint(f'{studentGrades}')
The output for the above code is as follows:
Index(['Math', 'Science', 'English'], dtype='object')Math Science English0 88 94 891 92 77 802 79 90 953 85 78 81Index(['Algebra', 'Biology', 'Literature'], dtype='object')Algebra Biology Literature0 88 94 891 92 77 802 79 90 953 85 78 81
Codebyte Example
The following Codebyte Example demonstrates how to view and update the column labels of a DataFrame using the .columns
attribute:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.