บทนำ
ใช้เมธอด to_tuples() ของ IntervalArray เพื่อแปลงช่วง (intervals) เป็น ndarray ของทูเพิล (left, right)
ขั้นตอน
1. นำเข้าไลบรารี
import pandas as pd
2. สร้าง IntervalArray จากจุดแบ่ง (breaks)
index = pd.arrays.IntervalArray.from_breaks(range(5))
สร้างช่วง: (0,1], (1,2], (2,3], (3,4] — ปิดขวา (right-closed) เป็นค่าเริ่มต้น
3. แปลงเป็นทูเพิล
print("\nThe ndarray of Tuples...\n", index.to_tuples())
ตัวอย่างโค้ดเต็ม
import pandas as pd
index = pd.arrays.IntervalArray.from_breaks(range(5))
print("IntervalIndex...\n", index)
print("\nIntervalIndex length...\n", index.length)
print("\nThe ndarray of Tuples...\n", index.to_tuples())
ผลลัพธ์
IntervalIndex...
[(0, 1], (1, 2], (2, 3], (3, 4]]
Length: 4, dtype: interval[int64, right]
IntervalIndex length...
Int64Index([1, 1, 1, 1], dtype='int64')
The ndarray of Tuples...
[(0, 1) (1, 2) (2, 3) (3, 4)]
คำอธิบาย
from_breaks([0,1,2,3,4])สร้าง 4 ช่วง: (0,1], (1,2], (2,3], (3,4]to_tuples()คืนค่า numpy array ของ tuples:[(0,1), (1,2), (2,3), (3,4)]- ค่า left, right เป็นค่าตัวเลข ไม่รวมข้อมูล closed/open
- ใช้งานง่ายสำหรับการ export หรือการคำนวณต่อ