loc vs iloc
今天要跟大家介紹loc與iloc的差異,以下是官方文件的介紹
loc: Access a group of rows and columns by label(s) or a boolean array.
iloc: Purely integer-location based indexing for selection by position.
解釋
- loc 是基於行標籤和列標籤(x_label、y_label)進行索引
- iloc 是基於行索引和列索引(index,columns)
範例(loc與iloc實作比較)
### 隨機生DataFrame 型別資料
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1, 20, size=(5,4)),index=list('abcde'),columns=list('ABCD'))
print(df)
| A | B | C | D |
a | 18 | 11 | 18 | 6 |
b | 8 | 6 | 17 | 11 |
c | 7 | 4 | 16 | 8 |
d | 1 | 10 | 14 | 10 |
e | 11 | 13 | 4 | 5 |
loc
#取 a row和 A column對應的資料
print(df.loc['a','A'])
#取a, b row和A, B column對應資料
print(df.loc['a':'b','A':'B'])
iloc
#使用0 row 0 column取 a 和 A 對應的資料
print(df.iloc[0,0])
#使用0:2 row 0:2 column取 a:b 和 A:B 對應的資料
print(df.iloc[0:2,0:2])
程式設計實作題