Example
df = pd.DataFrame([('bird', 389.0),
('bird', 24.0),
('mammal', 80.5),
('mammal', np.nan)],
index=['falcon', 'parrot', 'lion', 'monkey'],
columns=('class', 'max_speed'))
df.index
# output
# Index(['falcon', 'parrot', 'lion', 'monkey'], dtype='object')
df.columns
# output
# Index(['class', 'max_speed'], dtype='object')
df.columns=['Class', 'Max_speed']
df.index=['Falcon', 'Parrot', 'Lion', 'Monkey']
pandas.rename官方文档
Series.rename(index=None, *, axis=None, copy=True, inplace=False, level=None, errors=‘ignore’)
df.rename(index={'Falcon':'falcon', 'Parrot':'parrot', 'Lion':'lion', 'Monkey':'monkey'},
columns={'Class':'class', 'Max_speed':'max_speed'}, inplace=True)
pandas.DataFrame.set_index官方文档
DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
设置 ‘class’ 为索引列
df.set_index('class')
df.set_index('class', drop=False)
df.set_index('class', append=True)
设置多索引
df.set_index([pd.index([1, 2, 3, 4]), 'class'])
pandas.DataFrame.reset_index 官方文档
DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=’’)
重新设置索引
df.reset_index()
删除序索引列
df.reset_index(drop=True)
设置多列索引
df.set_index(['index', 'class'], inplace=True)
df.reset_index('index')
df.reset_index(['index', 'class'])