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

Python Pandas - สร้าง DataFrame คงดัชนีและชื่อเดิม (index.to_frame)

ในการสร้าง DataFrame จากดัชนี (Index) โดยคงดัชนีและชื่อเดิมไว้ ให้ใช้เมธอด index.to_frame() ใน Pandas โดยไม่ระบุพารามิเตอร์ index (ค่าเริ่มต้นคือ True)

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

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

import pandas as pd

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

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

3. แสดงดัชนี

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

4. แปลงเป็น DataFrame (คงดัชนีเดิม)

print("\nIndex to DataFrame...\n", index.to_frame())

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

import pandas as pd

# สร้างดัชนี Pandas
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)

# แปลงเป็น DataFrame (คงดัชนีเดิม)
print("\nIndex to DataFrame...\n", index.to_frame())

ผลลัพธ์

Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Number of elements in the index... 5
The dtype object... object
Index to DataFrame...                 Products
Products
Electronics      Electronics
Accessories    Accessories
Decor                  Decor
Books                  Books
Toys                   Toys

คำอธิบาย

เมื่อไม่ระบุ index (หรือตั้งค่า True) ดัชนีเดิมจะกลายเป็นทั้ง ดัชนีของ DataFrame และ คอลัมน์เดียว ชื่อคอลัมน์จะเหมือนชื่อดัชนีเดิม