Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Trả về tuple hình dạng dữ liệu Index

Để trả về tuple biểu diễn hình dạng (shape) của dữ liệu Index cơ bản, hãy sử dụng thuộc tính index.shape.

Các bước thực hiện

1. Import thư viện cần thiết

import pandas as pd

2. Tạo Index

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

3. Hiển thị Index

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

4. Lấy tuple hình dạng dữ liệu

print("\nTuple hình dạng dữ liệu...\n", index.shape)

Ví dụ hoàn chỉnh

import pandas as pd

# Tạo Index
index = pd.Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'])

# Hiển thị Index
print("Pandas Index...\n", index)

# Mảng dữ liệu
print("\nMảng dữ liệu (values)...\n", index.values)

# Tuple hình dạng dữ liệu
print("\nTuple hình dạng dữ liệu...\n", index.shape)

Kết quả đầu ra

Pandas Index...
Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')
Mảng dữ liệu (values)...
['Car' 'Bike' 'Truck' 'Car' 'Airplane']
Tuple hình dạng dữ liệu...
(5,)

Giải thích: Tuple trả về có dạng (n,) với n là số phần tử. Đối với Index 1 chiều, shape luôn có 1 phần tử. Tương tự index.values.shape.