python pandas是如何读取excel表中的sheet的(三)

今天继续pandas中的read_excel方法,重点介绍index_col入参。该参数的主要意义在于给每行作一个标记。
下面是官方给出的英文说明:
index_col : int, list of int, default None
(该参数接受int或者int类型的列表,默认为None,若是为None,则从第一行开始以0为开始,依次递增,据个人测试,列名的字符串形式也是能够的)
Column (0-indexed) to use as the row labels of the DataFrame.
Pass None if there is no such column. If a list is passed,
those columns will be combined into a MultiIndex. If a
subset of data is selected with usecols, index_col
is based on the subset.
一、代码解释python

# index_col为None同时也是默认值,默认会将第一行指定为0,后续依次递增
df = pd.read_excel(r'D:/myExcel/1.xlsx', sheet_name='Sheet1', index_col=None)
>>> df
name math Chinese
0 bob 23 12
1 millor 32 32
2 jiken 61 89
3 tom 34 94
4 json 83 12
5 dela 96 67
6 rison 90 34

# index_col指定为0,表明以第一列为行标
>>> df = pd.read_excel(r'D:/myExcel/1.xlsx', sheet_name='Sheet1', index_col=0)
>>> df
math Chinese
name
bob 23 12
millor 32 32
jiken 61 89
tom 34 94
json 83 12
dela 96 67
rison 90 34
>>> df.index
Index(['bob', 'millor', 'jiken', 'tom', 'json', 'dela', 'rison'], dtype='object', name='name')

# 指定index_col为前两列
>>> df = pd.read_excel(r'D:/myExcel/1.xlsx', sheet_name='Sheet1', index_col=[0,1])
>>> df
Chinese
name math
bob 23 12
millor 32 32
jiken 61 89
tom 34 94
json 83 12
dela 96 67
rison 90 34
>>> df.index
MultiIndex([( 'bob', 23),
('millor', 32),
( 'jiken', 61),
( 'tom', 34),
( 'json', 83),
( 'dela', 96),
( 'rison', 90)],
names=['name', 'math'])

# 通过测试,直接指定列名也是能够的,方便了不少
>>> df = pd.read_excel(r'D:/myExcel/1.xlsx', sheet_name='Sheet1', index_col='name')
>>> df
math Chinese
name
bob 23 12
millor 32 32
jiken 61 89
tom 34 94
json 83 12
dela 96 67
rison 90 34

哈哈,以上就是关于read_excel()方法中index_col的介绍,有兴趣的话能够关注个人微信公众号:python小工具,还有福利哦。
json


本文分享自微信公众号 - python小工具(pythonSmallTools)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。微信

相关文章
相关标签/搜索