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

Python Pandas - ทำซ้ำองค์ประกอบของ Index

การทำซ้ำองค์ประกอบใน Pandas Index

ใน Pandas สามารถทำซ้ำองค์ประกอบของ Index ได้โดยใช้เมธอด index.repeat() โดยระบุจำนวนครั้งที่ต้องการทำซ้ำเป็นอาร์กิวเมนต์

ขั้นตอนการทำซ้ำ Index

  1. นำเข้าไลบรารี pandas
  2. สร้าง Index พร้อมกำหนดชื่อ
  3. แสดง Index เดิม
  4. ใช้เมธอด repeat() เพื่อทำซ้ำองค์ประกอบ

ตัวอย่างโค้ด

import pandas as pd

# สร้าง Pandas Index
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], name='Transport')

# แสดง Index เดิม
print("Pandas Index...\n", index)

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

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

# ทำซ้ำแต่ละองค์ประกอบ 2 ครั้ง
print("\nResult after repeating each index element twice...\n", index.repeat(2))

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport')
Number of elements in the index... 6
The dtype object... object
Result after repeating each index element twice... Index(['Car', 'Car', 'Bike', 'Bike', 'Airplane', 'Airplane', 'Ship', 'Ship', 'Truck', 'Truck', 'Suburban', 'Suburban'], dtype='object', name='Transport')

คำอธิบายเพิ่มเติม

เมธอด repeat() จะคืนค่า Index ใหม่ที่องค์ประกอบแต่ละตัวถูกทำซ้ำตามจำนวนที่ระบุ ชื่อของ Index (name) จะถูกเก็บไว้เหมือนเดิม สามารถนำไปใช้ต่อได้ในการขยายข้อมูลหรือสร้างข้อมูลทดสอบ