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

Cách truy xuất phần tử trong Series dùng index (có thể tùy chỉnh) trong Python

Nếu dùng giá trị mặc định làm index trong Series, truy xuất bằng indexing. Nếu index tùy chỉnh, truyền như giá trị index và hiển thị.

Hãy hiểu qua ví dụ:

Ví dụ

import pandas as pd

my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)

print("Series chứa các phần tử:")
print(my_series)

print("Truy xuất phần tử dùng index tùy chỉnh:")
print(my_series['mn'])

print("Truy xuất phần tử dùng index tùy chỉnh:")
print(my_series['az'])

Đầu ra

Series chứa các phần tử:
ab    34
mn    56
gh    78
kl    90
wq    123
az    45
dtype: int64
Truy xuất phần tử dùng index tùy chỉnh:
56
Truy xuất phần tử dùng index tùy chỉnh:
45

Giải thích

  • Nhập thư viện cần thiết, đặt bí danh để dễ dùng.
  • Tạo danh sách giá trị dữ liệu, truyền cho hàm Series trong pandas.
  • Lưu các giá trị index tùy chỉnh (truyền sau) trong danh sách.
  • Tạo series, truyền index list và data làm tham số.
  • In series ra console.
  • Vì index tùy chỉnh, dùng series_name['index_name'] truy xuất.
  • In ra console.

Tóm tắt các cách truy xuất Series:

  • Label indexing: s['label'] - Trả về scalar
  • Positional indexing: s[0] - Trả về scalar (nếu index mặc định 0-based)
  • Slicing label: s['a':'c'] - Bao gồm cả 2 đầu (khác Python slicing)
  • Slicing positional: s[0:3] - Loại trừ cuối (Python standard)
  • Explicit: s.loc['label'], s.iloc[0]