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

Python - Tạo view mới (new view) của Pandas Index

Để tạo một view mới (new view) của Pandas Index với kiểu dữ liệu khác, sử dụng phương thức index.view(). View chia sẻ cùng bộ nhớ dữ liệu với Index gốc.

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

  1. Import thư viện: import pandas as pd
  2. Tạo Index: index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30]) (dtype int64)
  3. Gọi index.view('uint8') để tạo view với dtype uint8 (1 byte).

Ví dụ hoàn chỉnh

import pandas as pd

index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
print("Pandas Index...\n", index)
print("\nNumber of elements in the index...\n", index.size)
print("\nThe dtype object...\n", index.dtype)

# Tạo view mới với dtype uint8
res = index.view('uint8')
print("\nThe new view...\n", res)

# View chia sẻ cùng dữ liệu gốc
print("\nView for 0th index...\n", res[0])   # 50
print("\nView for 1st index...\n", res[1])   # 0 (byte thứ 2 của 50 trong int64 little-endian)

Kết quả

Pandas Index...
 Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64')
Number of elements in the index...
 9
The dtype object... int64
The new view...
 [ 50  0  0  0  0  0  0  0  10  0  0  0  0  0  0  0  70  0  0  0  0  0  0  0 110  0  0  0  0  0  0  0  90  0  0  0  0  0  0  0  50  0  0  0  0  0  0  0 110  0  0  0  0  0  0  0  90  0  0  0  0  0  0  0  30  0  0  0  0  0  0  0]
View for 0th index... 50
View for 1st index... 0

Giải thích: Mỗi int64 (8 byte) được nhìn như 8 giá trị uint8. Giá trị 50 = 0x32 → byte đầu tiên là 50, 7 byte còn lại là 0. Giá trị 10 = 0x0A → byte đầu tiên là 10. view() hữu ích cho thao tác thấp cấp (low-level) trên bộ nhớ.