Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
dataframe
communitycreator

How to return the labels of columns of a DataFrame in pandas

Onyejiaku Theophilus Chidalu

Overview

We use the DataFrame.columns attribute to return the labels of the columns of a DataFrame in pandas.

Syntax

Here is the syntax of the DataFrame.columns attribute:

DataFrame.columns
Syntax of the DataFrame.columns attribute

Parameter value

The DataFrame.columns is an attribute and, therefore, it takes no parameter value.

Return value

The DataFrame.columns attribute returns the column labels of a DataFrame.

Example

import pandas as pd

# creating a list of objects
int_values = [1, 2, 3, 4, 5]
text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
float_values = [0.0, 0.25, 0.5, 0.75, 1.0]

# creating a dataframe from the list of objects
df = pd.DataFrame({"int_column": int_values, "text_column": text_values,
                  "float_col": float_values})

print(df)
# obtaining the column labels of the dataframe
a = df.columns
print(a)
Implementing the DataFrame.columns atttribute

Explanation

  • Line 1: We import the pandas module.
  • Lines 4–6: We create a list of objects, text_values, int_values, and float_values.
  • Line 9: We create a DataFrame using the list of objects that we created with the pandas.DataFrame() function. The name of the DataFrame is df.
  • Line 12: We print the DataFrame, df.
  • Line 14: We obtain the labels of the DataFrame, df, by calling the DataFrame.columns attribute. Then, we assign the result to a variable called a.
  • Line 15: We print the value of a, which contains the column labels of df.

RELATED TAGS

pandas
dataframe
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring