第一期 Python 程式設計入門共學營作業任務十八


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
a 18
#取a, b row和A, B column對應資料
print(df.loc['a':'b','A':'B'])
A B
a 18 11
b 8 6

iloc

#使用0 row 0 column取 a 和 A 對應的資料
print(df.iloc[0,0])
A
a 18
#使用0:2 row 0:2 column取 a:b 和 A:B 對應的資料
print(df.iloc[0:2,0:2])
A B
a 18 11
b 8 6

程式設計實作題

#第一期Python程式設計入門共學營






你可能感興趣的文章

Day 175

Day 175

[React 02] Component 、 JSX、事件機制

[React 02] Component 、 JSX、事件機制

[4] 運算子 + 條件判斷

[4] 運算子 + 條件判斷






留言討論