python读取excel指定行列_pandas读取excel指定行列索引header和index_col参数

本文详细介绍了如何使用pandas的read_excel函数从Excel文件中读取数据,包括设置列索引(header)和行索引(index_col),并展示了实际代码演示。重点讲解了header参数的不同用法及index_col参数在设置DataFrame行索引时的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pandas读取excel文件sheet中的数据后会转为DataFrame对象,DataFrame对象是有行索引和列索引的,所以read_excel函数有2个参数来对行列索引进行设置。

1、指定哪一个作为列索引:header参数

2、指定哪一列作为行索引:index_col参数

header参数可选类型:

int类型:header参数为0,也就是第一行作为列索引(理解为表头)

list类型:[0,1] 多行索引MultiIndex

默认值:0

index_col参数可选类型:

int类型:0、1、2分别对应第一列、二列、三列

list类型:多行索引MultiIndex

默认值:None。此时程序会给自动给df加一个位置索引(0、1、2、3、4...)

代码演示header参数:

# -*- coding: utf-8 -*-

import pandas as pd

# 读取第一个sheet,默认header为0

df1 = pd.read_excel('aa.xlsx')

print(df1)

print('------------')

df2 = pd.read_excel('aa.xlsx',header=1)

print(df2)

print('------------')

df3 = pd.read_excel('aa.xlsx',header=[1,2])

print(df3)

print('--------------')

# 重置列索引

df = pd.read_excel('aa.xlsx')

df.columns = ['id','name','性别']

print(df)

1 a 男

0 2 b 男

1 3 c 男

2 4 d 女

3 5 e 妖

------------

2 b 男

0 3 c 男

1 4 d 女

2 5 e 妖

------------

2 b 男

3 c 男

0 4 d 女

1 5 e 妖

--------------

id name 性别

0 2 b 男

1 3 c 男

2 4 d 女

3 5 e 妖

代码演示index_col参数:

# -*- coding: utf-8 -*-

import pandas as pd

# 读取第一个sheet,默认header为0

df1 = pd.read_excel('aa.xlsx')

print(df1)

print('------------')

df2 = pd.read_excel('aa.xlsx',index_col=1)

print(df2)

print('------------')

df3 = pd.read_excel('aa.xlsx',index_col=[1,2])

print(df3)

print('--------------')

# 重置行索引

df = pd.read_excel('aa.xlsx')

df.index = ['row1','row2','row3','row4']

print(df)

1 a 男

0 2 b 男

1 3 c 男

2 4 d 女

3 5 e 妖

------------

1 男

a

b 2 男

c 3 男

d 4 女

e 5 妖

------------

1

a 男

b 男 2

c 男 3

d 女 4

e 妖 5

--------------

1 a 男

row1 2 b 男

row2 3 c 男

row3 4 d 女

row4 5 e 妖

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值