How to return the labels of columns of a DataFrame in pandas
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
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 objectsint_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 objectsdf = pd.DataFrame({"int_column": int_values, "text_column": text_values,"float_col": float_values})print(df)# obtaining the column labels of the dataframea = df.columnsprint(a)
Explanation
Line 1: We import the
pandasmodule.Lines 4–6: We create a list of objects,
text_values,int_values, andfloat_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 isdf.Line 12: We print the DataFrame,
df.Line 14: We obtain the labels of the DataFrame,
df, by calling theDataFrame.columnsattribute. Then, we assign the result to a variable calleda.Line 15: We print the value of
a, which contains the column labels ofdf.