We use the DataFrame.columns
attribute to return the labels of the columns of a DataFrame in pandas.
Here is the syntax of the DataFrame.columns
attribute:
DataFrame.columns
The DataFrame.columns
is an attribute and, therefore, it takes no parameter value.
The DataFrame.columns
attribute returns the column labels of a DataFrame.
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)
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
.