pandas获取Excel表中的数据主要通过label或者position获取。今天主要学习如何通过Label获取,其中又包含两部分:第一部分,如何快速获取某一列的数据或者某几行的数据;第二部分,如何通过loc获取某一区域(cross)的数据。
1、获取某一列的数据。
>>> import pandas as pd
>>> df = pd.read_excel(r'D:\myExcel\1.xlsx', 'Sheet1')
>>> df
name math science
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
# 获取name列的数据有两种方法,如下所示
# Selecting a single column, which yields a Series, equivalent to df.A
>>> df['name']
0 bob
1 millor
2 jiken
3 tom
4 json
5 dela
6 rison
Name: name, dtype: object
>>> df.name
0 bob
1 millor
2 jiken
3 tom
4 json
5 dela
6 rison
Name: name, dtype: object
2、获取某一行或者某几行的数据
Selecting via [], which slices the rows.
>>> df[0:1]
name math science
0 bob 23 12
>>> df[0:3]
name math science
0 bob 23 12
1 millor 32 32
2 jiken 61 89
>>>
3、使用loc[]获取某一区域的数据loc接受两个参数,第一个参数为行的index(在读取excel时,如果未指定则会默认添加一列数字为index)的列表或者切片,第二个参数可以为列的Label(index)的列表或者切片。下面举例说明:
# 如果没有第二个值,则默认为获取整行数据
# 获取某一行的数据
>>> df.loc[0]
name bob
math 23
science 12
Name: 0, dtype: object
# 通过列表获取指定的整行数据,如下所示,获取0行和3行的数据
>>> df.loc[[0,3]]
name math science
0 bob 23 12
3 tom 34 94
# 通过切片获取0-3行的整行数据
>>> df.loc[0:3]
name math science
0 bob 23 12
1 millor 32 32
2 jiken 61 89
3 tom 34 94
# 获取某一列或者某几列的数据
>>> df.loc[:,['name', 'math']]
name math
0 bob 23
1 millor 32
2 jiken 61
3 tom 34
4 json 83
5 dela 96
6 rison 90
# 通过指定某几行以及列的切片获取指定位置的数据
>>> df.loc[[0,1],'name':'math']
name math
0 bob 23
1 millor 32
哈哈,以上就是pandas获取Excel中的数据的一种常用方法,本文重点介绍了loc方法,其需要传入两个参数,一个确定行一个确定列,均可以以列表或者切片的形式传入。如果您对pandas以及excel有兴趣,欢迎关注我的公众号:python小工具。