Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - คำนวณตัวดัชนีสไลด์สำหรับฉลากอินพุต

เพื่อคำนวณตัวดัชนีสไลด์ (slice indexer) สำหรับฉลากอินพุต ให้ใช้เมธอด index.slice_indexer() ก่อนอื่น ให้นำเข้าไลบรารีที่จำเป็น:

import pandas as pd

สร้างออบเจกต์ Pandas Index:

index = pd.Index(list('pqrstuvwxyz'))

แสดง Pandas Index:

print("Pandas Index...\n", index)

ดึงตัวดัชนีสไลด์ start คือฉลากเริ่มต้น end คือฉลากสิ้นสุด:

print("\nThe slice indexer with start and stop...\n", index.slice_indexer(start='s', end='w'))

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd
# สร้าง Pandas index object
index = pd.Index(list('pqrstuvwxyz'))
# แสดง Pandas index
print("Pandas Index...\n", index)
# คืนค่าจำนวนสมาชิกใน Index
print("\nNumber of elements in the index...\n", index.size)
# ดึงตัวดัชนีสไลด์
# start คือฉลากเริ่มต้น
# end คือฉลากสิ้นสุด
print("\nThe slice indexer with start and stop...\n", index.slice_indexer(start='s', end='w'))

ผลลัพธ์

โค้ดจะให้ผลลัพธ์ดังนี้:

Pandas Index... Index(['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], dtype='object')
Number of elements in the index... 11
The slice indexer with start and stop... slice(3, 8, None)