Hiểu cách dùng toán tử cắt : để truy cập các phần tử trong khoảng nhất định của Series.
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)
n = 3
print("3 phần tử cuối:")
print(my_series[n:])
Kết quả
Series chứa các phần tử: ab 34 mn 56 gh 78 kl 90 wq 123 az 45 dtype: int64 3 phần tử cuối: kl 90 wq 123 az 45 dtype: int64
Giải thích
- Nhập pandas, tạo dữ liệu và index tùy chỉnh.
- Tạo Series từ dữ liệu và index.
- Toán tử
:cho phép truy cập phạm vi:[lower:upper]bao gồm lower, loại trừ upper. my_series[n:]nghĩa là từ chỉ số n đến cuối (vì upper mặc định là len-1).- Với n=3, lấy các phần tử từ index 3 (kl) đến hết.