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

Python Pandas - Trả về đối tượng dtype của dữ liệu Index

Để trả về đối tượng dtype (kiểu dữ liệu) của dữ liệu Index cơ bản, hãy sử dụng thuộc tính index.dtype.

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', 'Shop', 'Car', 'Airplace', 'Truck'])

3. Hiển thị Index

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

4. Lấy đối tượng dtype

print("\nĐối tượng dtype...\n", index.dtype)

Ví dụ hoàn chỉnh

import pandas as pd

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

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

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

# Đối tượng dtype
print("\nĐối tượng dtype...\n", index.dtype)

# 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', 'Shop', 'Car', 'Airplace', 'Truck'], dtype='object')
Mảng dữ liệu (values)...
['Car' 'Bike' 'Shop' 'Car' 'Airplace' 'Truck']
Đối tượng dtype...
object
Tuple hình dạng dữ liệu...
(6,)

Giải thích: dtype trả về numpy dtype object ('object' cho chuỗi). Không nhầm lẫn với inferred_type - dtype là kiểu lưu trữ thực tế, inferred_type là kiểu suy luận ngữ nghĩa.