Giả sử bạn có time series và kết quả 3 ngày đầu và 3 ngày cuối từ series cho trước như sau:
first three days: 2020-01-01 Chennai 2020-01-03 Delhi Freq: 2D, dtype: object last three days: 2020-01-07 Pune 2020-01-09 Kolkata Freq: 2D, dtype: object
Để giải quyết bài toán này, chúng ta sẽ làm theo các bước dưới đây:
Giải pháp
- Định nghĩa một Series và lưu vào data
- Áp dụng pd.date_range() với start='2020-01-01', periods=5, freq='2D', lưu vào time_series
time_series = pd.date_range('2020-01-01', periods=5, freq='2D')
- Gán data.index = time_series
- In 3 ngày đầu dùng data.first('3D'), lưu vào first_day
first_day = data.first('3D')
- In 3 ngày cuối dùng data.last('3D'), lưu vào last_day
last_day = data.last('3D')
Ví dụ
Hãy kiểm tra mã sau để hiểu rõ hơn:
import pandas as pd
data = pd.Series(['Chennai', 'Delhi', 'Mumbai', 'Pune', 'Kolkata'])
time_series = pd.date_range('2020-01-01', periods=5, freq='2D')
data.index = time_series
print("time series:\n", data)
first_day = data.first('3D')
print("first three days:\n", first_day)
last_day = data.last('3D')
print("last three days:\n", last_day)
Đầu ra
time series: 2020-01-01 Chennai 2020-01-03 Delhi 2020-01-05 Mumbai 2020-01-07 Pune 2020-01-09 Kolkata Freq: 2D, dtype: object first three days: 2020-01-01 Chennai 2020-01-03 Delhi Freq: 2D, dtype: object last three days: 2020-01-07 Pune 2020-01-09 Kolkata Freq: 2D, dtype: object