开发手册 欢迎您!
软件开发者资料库

Python pandas dataframe iloc 和 loc 的用法及区别

本文主要介绍Python中,pandas dataframe的iloc 和 loc 的用法及区别,以及相关的示例代码。

1、iloc的用法

参考文档Python pandas.DataFrame.iloc函数方法的使用

2、loc的用法

参考文档Python pandas.DataFrame.loc函数方法的使用

3、iloc和loc的区别

主要区别是loc获取具有特定label的行(and/or 列)。Iloc获取整数location上的行(and/or 列)。

例如,

>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 49    a48    b47    c0     d1     e2     f>>> s.loc[0]    # 在索引标签0处的值'd'>>> s.iloc[0]   # 值在索引位置0'a'>>> s.loc[0:1]  # 索引标签在0和1之间的行(包括)0    d1    e>>> s.iloc[0:1] # 索引位置在0和1之间的行(不包括)49    a

.loc应该基于索引标签而不是位置,所以它类似于Python基于字典的索引。但是,它可以接受布尔数组、切片和标签列表(这些都不能与Python字典一起使用)。

.iloc基于索引位置进行查找,也就是说,pandas的行为类似于Python列表。如果在该位置没有索引,pandas将引发IndexError。

例如,

>>> s = pd.Series([11, 9], index=["1990", "1993"], name="Magic Numbers")>>> s1990    111993     9Name: Magic Numbers , dtype: int64>>> s.iloc[0]11>>> s.iloc[-1]9>>> s.iloc[4]Traceback (most recent call last):    ...IndexError: single positional indexer is out-of-bounds>>> s.iloc[0:3] # slice1990 111993  9Name: Magic Numbers , dtype: int64>>> s.iloc[[0,1]] # list1990 111993  9Name: Magic Numbers , dtype: int64>>> s.loc['1990']11>>> s.loc['1970']Traceback (most recent call last):    ...KeyError: ’the label [1970] is not in the [index]’>>> mask = s > 9>>> s.loc[mask]1990 11Name: Magic Numbers , dtype: int64>>> s.loc['1990':] # slice1990    111993     9Name: Magic Numbers, dtype: int64