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

Python Pandas - หารูปร่างของข้อมูลดัชนี (index.shape)

ในการหาทูเพิล (tuple) ที่แสดงรูปร่างของข้อมูลในดัชนี (Index) ให้ใช้คุณสมบัติ index.shape ใน Pandas

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

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

import pandas as pd

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

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

3. แสดงดัชนี

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

4. หารูปร่างของข้อมูล

print("\nA tuple of the shape of underlying data...\n", index.shape)

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

import pandas as pd

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

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

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

# หารูปร่างของข้อมูล
print("\nA tuple of the shape of underlying data...\n", index.shape)

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')
Array... ['Car' 'Bike' 'Truck' 'Car' 'Airplane']
A tuple of the shape of underlying data... (5,)

คำอธิบาย

index.shape คืนค่าทูเพิลที่แสดงรูปร่างของข้อมูล สำหรับดัชนี 1 มิติ จะเป็น (n,) โดย n คือจำนวนองค์ประกอบ