dataframe行列索引设置与转换
1. 获取行列索引Exampledf = pd.DataFrame([('bird', 389.0),('bird', 24.0),('mammal', 80.5),('mammal', np.nan)],index=['falcon', 'parrot', 'lion', 'monkey'],columns=
·
1. 获取行列索引
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')
2. 修改行列索引
2.1 暴力修改(必须修改全部索引)
- 修改列索引
df.columns=['Class', 'Max_speed']
- 修改行索引
df.index=['Falcon', 'Parrot', 'Lion', 'Monkey']
2.2 pd.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)
3. 列与索引的互相转化
3.1 列转换成索引
pandas.DataFrame.set_index官方文档
DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
- keys: 设置为索引的列名,以list的形式表示
- 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'])
3.2 将索引转换为列
pandas.DataFrame.reset_index 官方文档
DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=’’)
- level: 用于指定要将层次化索引的第几层转化为columns,第一个索引为0级,第二个为1级,默认为None(全部索引)。也可以用list的形式表示
- drop: 是否删除索引列,默认False。
- inplace: 是否修改原数据
- col_level: 当有多列索引时,选取特定层级转换为列
- 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'])
更多推荐
已为社区贡献8条内容
所有评论(0)