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

Python Pandas - สร้างดัชนีใหม่จากตำแหน่งที่เลือก (index.take)

ในการสร้างดัชนี (Index) ใหม่จากค่าที่เลือกตามตำแหน่ง (indices) ให้ใช้เมธอด index.take() ใน Pandas

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้างดัชนี

index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

3. แสดงดัชนี

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

4. เลือกค่าตามตำแหน่ง

print("\nA new Index of the values selected by the indices...\n", index.take([1, 2]))

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

import pandas as pd

# สร้างดัชนี
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

# แสดงดัชนี
print("Pandas Index...\n", index)

# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)

# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)

# เลือกตำแหน่งที่ 1 และ 2
print("\nA new Index of the values selected by the indices...\n", index.take([1, 2]))

ผลลัพธ์

Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Number of elements in the index... 5
The dtype object... object
A new Index of the values selected by the indices... Index(['Accessories', 'Decor'], dtype='object', name='Products')

คำอธิบาย

take([1, 2]) เลือกค่าตำแหน่งที่ 1 ('Accessories') และตำแหน่งที่ 2 ('Decor') สร้างดัชนีใหม่ที่มีชื่อเหมือนเดิม ตำแหน่งนับจาก 0