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

Python Pandas - Trả về mảng biểu diễn dữ liệu trong Index

Để trả về mảng NumPy biểu diễn dữ liệu trong Pandas Index, hãy sử dụng thuộc tính index.values.

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', 'Ship', 'Airplane'])

3. Hiển thị Index

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

4. Lấy mảng dữ liệu

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

Ví dụ hoàn chỉnh

import pandas as pd

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

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

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

# Chuyển vị (transpose) - Index 1D nên T trả về chính nó
print("\nChuyển vị của Index...\n", index.T)

Kết quả đầu ra

Pandas Index...
Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')
Mảng dữ liệu...
['Car' 'Bike' 'Truck' 'Ship' 'Airplane']
Chuyển vị của Index...
Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')

Lưu ý: values trả về numpy.ndarray. Đối với Index 1 chiều, .T (transpose) trả về chính Index đó vì chuyển vị không thay đổi cấu trúc 1D.