在对数据做相应操作之前,我们要先筛选出所需的数据,pandas提供了一些方法方便我们选取数据,这里主要讲解dataFrame类型的数据选取,Series类型用法类似,可以查阅文档中的相关属性。
pandas主要提供了三种属性用来选取行/列数据:
属性名 | 属性 |
---|---|
ix | 根据整数索引或者行标签选取数据 |
iloc | 根据位置的整数索引选取数据 |
loc | 根据行标签选取数据 |
在 0.20.0版本不支持ix这种混合选取的方法
这三种属性,既可以让我们获取整行/整列的数据,也可以让我们选取符合标准的行/列数据。下面举一些小例子来说明,更加丰富的例子可以看参考资料中*[pandas 0.23.4 documentation —— Indexing and Selecting Data]*
1. iloc
df.iloc[参数]
iloc提供了五种参数形式
input | example | output |
---|---|---|
整数(行索引) | df.iloc[5] | 选取第6行数据 |
整数数组 | df.iloc[[1,3,5]] | 选取第2,4,6行数据 |
整数切片 | df.iloc[1:3] | 选取2~4行数据(不包含第4行数据) |
布尔值数组 | df.iloc[[True,False,True] | 选取第1,3行数据 |
函数 | df.iloc[(df[‘one’]>10).tolist()] | 选取’one’这列大于10的那一行数据 |
注意:iloc接受有返回值的函数作为参数,但要保证函数返回的是整数/整数list,布尔值/布尔list
如果直接运行 df.iloc[df[‘one’]>10]
则会报错 NotImplementedError: iLocation based boolean indexing on an integer type is not available
因为df[‘one’] > 10 返回的是 series类型的数据
除此之外,还可以进行组合切片
input | example | output |
---|---|---|
整数(行索引) | df.iloc[5,1] | 选取第6行,第2列的数据 |
整数数组 | df.iloc[[1,3],[1,2]] | 选取第2,4行;2,3列的数据 |
整数切片 | df.iloc[1:3,1:3] | 选取第2,3行;2,3列的数据 |
布尔值数组 | df.iloc[[True,True,False],[True,False,True]] | 选取第1,2行;1,3列的数据 |
要注意的是,我们用df[参数]也可以进行切片,但这种方式容易引起chained indexing 问题。除此之外,**df[lable1][lable2]**的操作是线性的,对lable2的选取是在df[lable1]的基础上进行,速度相对较慢。所以在对数据进行切片的时候尽量使用iloc这类的方法
2. loc
loc也提供了五种参数形式
input | example(摘自官方文档) | output |
---|---|---|
行标签 | df.loc[‘viper’] | 选取viper那一行 |
行标签数组 | df.loc[[‘viper’, ‘sidewinder’]] | 选取行标签为viper、sidewinder |
行标签切片 | df.loc[‘cobra’:‘viper’, ‘max_speed’] | 选取从cobra到viper行的max_speed列 |
布尔值数组 | df.loc[[False, False, True]] | — |
函数 | df.loc[df[‘shield’] > 6, [‘max_speed’]] | 选取shield列大于6的那一行的max_speed数据 |
注意 df.loc[df[‘one’]>10]这样的写法是可以正常选出one列大于10的数据
3. ix
ix支持基于混合整数和标签的访问,它支持.loc和iloc的任何输入,还支持浮点标签。
4. values
df.values
运行该属性,会将DataFrame中数据以ndarray的类型返回回来, 所以我们在此基础上利用索引选取相应的行数据
df = pd.read_excel('test.xlsx')
print(df)
结果
print(df.values)
结果
print(df.values[1]) #选取第2行的数据
结果
5. at
访问行/列标签对的单个值。
6. iat
按整数位置访问行/列对的单个值。
参考资料
[pandas 0.23.4 documentation —— Indexing and Selecting Data]
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-integer
[pandas 0.23.4 documentation —— DataFrame ]
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html
[博客: pandas中Dataframe的查询方法([], loc, iloc, at, iat, ix)]
https://blog.csdn.net/wr339988/article/details/65446138
[pandas 0.23.4 documentation —— Returning a view versus a copy]
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
[stack overflow —— pandas iloc vs ix vs loc explanation, how are they different?]
[stack overflow —— When to use iloc and loc for boolean]
https://stackoverflow.com/questions/51585502/when-to-use-iloc-and-loc-for-boolean