Introduction
Columns and index attributes help you see and organize the labels of your data in tables. They make it easy to find and work with your data.
dataframe.columns dataframe.index
import pandas as pd data = {'Name': ['Anna', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) print(df.columns) print(df.index)
df.columns = ['First Name', 'Years'] print(df.columns)
df.index = ['a', 'b'] print(df.index)
import pandas as pd data = {'City': ['Paris', 'London', 'Berlin'], 'Population': [2148000, 8982000, 3769000]} df = pd.DataFrame(data) # Show original columns and index print('Columns:', df.columns) print('Index:', df.index) # Rename columns df.columns = ['City Name', 'Number of People'] # Change index labels df.index = ['a', 'b', 'c'] print('New Columns:', df.columns) print('New Index:', df.index)
columns attribute in a pandas DataFrame represent?columns in pandascolumns attribute stores the labels for each column in the DataFrame, like the headers in a table.index store row labels, not column names.df?index attribute in pandas stores the row labels or indices.columns is for column names; labels and rows are not valid pandas attributes.df below:import pandas as pd
df = pd.DataFrame({
'A': [1, 2],
'B': [3, 4]
}, index=['x', 'y'])
print(df.columns)df.columns returnsdf.columns returns an Index object listing the column names, which are 'A' and 'B'.import pandas as pd
df = pd.DataFrame({'X': [10, 20], 'Y': [30, 40]})
df.index = ['a', 'b', 'c']df.index, the length must match the number of rows exactly.df with columns ['name', 'age', 'city'] and default numeric index. How do you rename the columns to ['Name', 'Age', 'City'] and set the index to the 'name' column in one step?df.rename(columns=..., inplace=True) to rename columns safely without losing data.df.set_index('Name', inplace=True) to set the index to the 'Name' column after renaming.Pass the test and this pattern moves unknown