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

Python Pandas - ดึงอาร์เรย์ข้อมูลจากดัชนี (index.values)

ในการดึงอาร์เรย์ (NumPy array) ที่แทนข้อมูลในดัชนี (Index) ให้ใช้คุณสมบัติ index.values ใน Pandas

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

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

import pandas as pd

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

index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])

3. แสดงดัชนี

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

4. ดึงอาร์เรย์ข้อมูล

print("\nArray...\n", index.values)

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

import pandas as pd

# สร้างดัชนี
index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])

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

# ดึงอาร์เรย์ข้อมูล
print("\nArray...\n", index.values)

# แสดงทรานส์โพสของดัชนี
print("\nTranspose of the Pandas Index...\n", index.T)

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')
Array... ['Car' 'Bike' 'Truck' 'Ship' 'Airplane']
Transpose of the Pandas Index... Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')

คำอธิบาย

index.values คืนค่า NumPy array ของข้อมูลในดัชนี สามารถนำไปใช้กับการคำนวณหรือการดำเนินการของ NumPy ได้โดยตรง