What does the pandas DataFrame.columns attribute do?


The DataFrame is a pandas two-dimension data structure that is used to store the labeled data in a table format, a DataFrame has row index labels and column index labels which are used to represent the element (a value) address.

By using these row/column labels we can access elements of a DataFrame and we can do data manipulations too.

If you want to get the column labels from a DataFrame separately then we can use the pandas.DataFrame “columns” attribute.

Example 1

In this example, we have applied the columns attribute to the pandas DataFrame to get the column labels.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([['A', 'B', 'C', 'D', 'E', 'F']])

print("DataFrame:")
print(df)

# get the column labels
result = df.columns
print("Output:")
print(result)

Output

The output is as follows −

DataFrame:
  0 1 2 3 4 5
0 A B C D E F

Output:
RangeIndex(start=0, stop=6, step=1)

For this example, we haven’t initialized the column labels for the DataFrame while creating. And the column labels are assigned automatically by the pandas DataFrame Constructor.

Those labels are integer values ranging from 0 - length-1 are called RangeIndex values.

Example 2

Now, update the auto-created column name/labels by sending a list of values to the DataFrame.columns attribute “df.columns”.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([['A', 'B', 'C', 'D', 'E', 'F']])

print("DataFrame:")
print(df)

# set the column labels
df.columns = ['C1','C2','C3','C4','C5','C6']
print("Column names are Updated:")
print(df)

Output

The output is as follows −

DataFrame:
  0 1 2 3 4 5
0 A B C D E F

Column names are Updated:
  C1 C2 C3 C4 C5 C6
0  A  B  C  D  E  F

The column labels are updated from RangeIndex values to C1, C2, C3, C4, C5, C6 by sending these labels to the df.columns attribute.

Updated on: 08-Mar-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements