เข้าใจการใช้ slicing operator ':' เข้าถึงข้อมูลในช่วงของ Series
ตัวอย่าง
import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
print("The series contains following elements")
print(my_series)
n = 3
print("Bottom 3 elements are :")
print(my_series[n:])
ผลลัพธ์
The series contains following elements ab 34 mn 56 gh 78 kl 90 wq 123 az 45 dtype: int64 Bottom 3 elements are : kl 90 wq 123 az 45 dtype: int64
คำอธิบาย
- นำเข้า pandas ตั้ง alias
- สร้าง list ข้อมูล ส่งให้ Series()
- สร้าง custom index list
- ใช้ ':' operator เข้าถึงช่วง [lower:higher] รวม lower ไม่รวม higher
- ไม่ระบุ lower = 0, ไม่ระบุ higher = len-1
- ที่นี่ lower=3 higher=len-1 แสดง 3 องค์ประกอบท้าย
- พิมพ์ผลลัพธ์
นอกจากนี้ยังใช้ series.tail(n) ได้โดยตรงสำหรับ n องค์ประกอบท้าย