Discover schema
Before selecting fields dynamically, inspect available labels and compare them with required names.
Pandas · Pipe
DataFrame.columns gives access to a DataFrame’s column labels as a pandas Index. Read it to inspect labels and assign a new label sequence to rename the columns.
df.columns exposes a DataFrame’s column labels as a pandas Index. Read it to inspect labels or use it in selection and alignment workflows; assigning a same-length label sequence replaces the DataFrame’s column names.
DataFrame.columnspandas.Index — the column labels of the DataFrame.
df.columns identifies the labels along the DataFrame’s column axis.Index, preserving the column-label axis abstraction.df.columns instead of mutating individual Index entries.import pandas as pd
df = pd.DataFrame({"name": ["Ada", "Linus"], "score": [98, 95]})
print(df.columns)
print(df["score"])
df.columns = ["student", "points"]
print(df)Inspect the column labels, select a column by label, then replace all labels with a new same-length sequence.
Before selecting fields dynamically, inspect available labels and compare them with required names.
Replace the complete set of column names after loading data with inconsistent headers.
Use column labels when building selections or aligning DataFrame operations.
df.columns return?DataFrame.columns returns the labels for the DataFrame’s columns as a pandas Index. It represents the column names rather than the row index.
Follow-up: How would you obtain a plain Python list? Convert the result explicitly, for example with df.columns.tolist().
df.columns be used to rename columns?Use df.columns to inspect the current labels, and assign a new sequence to rename all columns. The replacement labels should correspond one-for-one with the existing columns.
Follow-up: How would you rename only one column? Use a label-mapping operation such as df.rename(columns={old: new}), preserving the other labels.
df.columns differ from df.index?Column labels are separate from row labels: df.columns describes the DataFrame’s column axis, while df.index describes its row axis. Both are axis-label objects used by DataFrame operations.
Follow-up: What related attribute exposes both axes? df.axes returns a list representing the DataFrame’s axes.
DataFrame.indexDataFrame.axes