iloc 和 loc 是 Pandas 中对 DataFrame 进行切片的两种方法。这两种方法都可用于选择行和列,但它们在解释输入的方式上有所不同。
loc 获取具有特定 标签的行(和/或列)。
iloc 在整数位置处获取行(和/或列)。
为了进行演示,请考虑一系列具有非单调整数索引的字符:
>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 49 a 48 b 47 c 0 d 1 e 2 f
s.loc[0] # value at index label 0 'd' s.iloc[0] # value at index location 0 'a' s.loc[0:1] # rows at index labels between 0 and 1 (inclusive) 0 d 1 e s.iloc[0:1] # rows at index location between 0 and 1 (exclusive) 49 a
以下是传递各种对象时 s.loc 和 s.iloc 之间的一些差异/相似之处:
Object | Description | s.loc[Object] | s.iloc[Object] |
---|---|---|---|
0 | Single item | Value at index label 0 (_the string 'd'_) | Value at index location 0 (_the string 'a'_) |
0:1 | Slice | Two rows (labels 0 and 1) | One row (first row at location 0) |
1:47 | Slice with out-of-bounds end | Zero rows (empty Series) | Five rows (location 1 onwards) |
1:47:-1 | Slice with negative step | three rows (labels 1 back to 47) | Zero rows (empty Series) |
[2, 0] | Integer list | Two rows with given labels | Two rows with given locations |
s > 'e' | Bool series (indicating which values have the property) | One row (containing 'f') | NotImplementedError |
(s>e).values | Bool array | One row (containing 'f') | Same as loc |
999 | Int object not in index | KeyError | IndexError (out of bounds) |
-1 | Int object not in index | KeyError | Returns last value in s |
lambda x: x.index[3] | Callable applied to series (here returning 3rd item in index) | s.loc[s.index[3]] | s.iloc[s.index[3]] |
以上是Pandas 的 DataFrame 切片'loc”和'iloc”方法之间的主要区别是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!