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

Python Pandas - Lấy vị trí nguyên (integer location) cho nhãn được yêu cầu

Để lấy vị trí nguyên (integer location) cho một nhãn được yêu cầu trong Pandas Index, sử dụng phương thức index.get_loc().

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

  1. Import thư viện: import pandas as pd
  2. Tạo Index từ danh sách ký tự: index = pd.Index(list('pqrstuvwxyz'))
  3. Gọi index.get_loc('w') và index.get_loc('z') để lấy vị trí.

Ví dụ hoàn chỉnh

import pandas as pd

# Tạo Pandas Index object
index = pd.Index(list('pqrstuvwxyz'))

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

# Số lượng phần tử
print("\nNumber of elements in the index...\n", index.size)

# Lấy vị trí nguyên cho nhãn 'w' và 'z'
print("\nDisplay integer location from given index...\n", index.get_loc('w'))  # 7
print("\nDisplay integer location from given index...\n", index.get_loc('z'))  # 10

Kết quả

Pandas Index...
 Index(['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], dtype='object')
Number of elements in the index...
 11
Display integer location from given index...
 7
Display integer location from given index...
 10

Giải thích: Chỉ số 0-based: 'p'=0, 'q'=1, ..., 'w'=7, ..., 'z'=10.