เราสามารถแบ่ง Pandas DataFrame เพื่อเลือกแถวระหว่างค่าดัชนีสองค่า มาดูตัวอย่างกันว่าทำอย่างไร
ขั้นตอน
- สร้างข้อมูลตารางแบบสองมิติ ปรับขนาดได้ และอาจต่างกันได้ df .
- พิมพ์ DataFrame อินพุต df .
- เริ่มต้นตัวแปรสำหรับขีดจำกัดล่างของดัชนี
- เริ่มต้นตัวแปรอื่นสำหรับขีดจำกัดบนของดัชนี
- ใช้ df[index_lower_limit:index_upper_limit] เพื่อพิมพ์ DataFrame ในดัชนีช่วง
ตัวอย่าง
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
index_lower_limit = 1
index_upper_limit = 3
print("DataFrame between two index values:\n",
df[index_lower_limit: index_upper_limit]) ผลลัพธ์
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 DataFrame between two index values: x y z 1 2 7 3 2 7 5 5