เราสามารถเข้าถึงข้อมูลใน Pandas Series ได้ 3 วิธีดังนี้
- ใช้ method Series.loc[] — ใส่ชื่อ label ที่อยู่ใน Series เท่านั้น
- ใช้ method Series.iloc[] — ใส่ตำแหน่ง index ของข้อมูลใน Series เท่านั้น
- ใช้ Series[] — ใส่เป็นตำแหน่ง index หรือ label ก็ได้
ต่อมาต้องดูว่าเราต้องการผลลัพธ์ที่ได้จากการ return ของ method เป็นข้อมูลชนิดใด ผลลัพธ์ที่ได้จากการ return สามารถ return ได้ 2 แบบดังนี้
- pandas.core.series.Series
- pandas.core.frame.DataFrame
pandas.core.series.Series
คือ return เป็น object หรือข้อมูลใน Series นั้น จะเป็นข้อมูลตัวเดียวเดี่ยวๆ จะใช้ [] คู่เดียว และใส่แค่ parameter เดียว หากใส่มากกว่านั้นจะได้ pandas.core.indexing.IndexingError: Too many indexers
ตัวอย่างเมื่อใช้ .loc
import pandas as pd
lst = pd.Series([3,5,2], index=['a','b','c'])
acc1 = lst.loc['a']
print(acc1)
output:
3
ตัวอย่างเมื่อใช้ .iloc
acc2 = lst.iloc[1]
print(acc2)
output:
5
ตัวอย่างเมื่อใช้ []
หากใส่มากกว่า 1 parameter ใน [] จะได้ KeyError: ‘key of type tuple not found and not a MultiIndex’
acc3 = lst[2]
acc4 = lst['c']
print(acc3, acc4)
output:
2 2
pandas.core.frame.DataFrame
คือการ return เป็น DataFrame จะใช้ [] สองคู่ และสามารถใส่ได้มากกว่า 1 parameter โดยไม่เกิด Error
ตัวอย่างเมื่อใช้ .loc
acc5 = lst.loc[['a','b']]
print(acc5)
output:
a 3
b 5
dtype: int64
ตัวอย่างเมื่อใช้ .iloc
acc6 = lst.iloc[[1,2]]
print(acc6)
output:
b 5
c 2
dtype: int64
ตัวอย่างเมื่อใช้ []
acc7 = lst[['b','c']]
print(acc7)
output:
b 5
c 2
dtype: int64