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中文網其他相關文章!