根據索引值截斷資料框時間序列資料的程式
假設您有一個包含時間序列資料的資料框,而截斷資料的計算結果是:
before truncate: Id time_series 0 1 2020-01-05 1 2 2020-01-12 2 3 2020-01-19 3 4 2020-01-26 4 5 2020-02-02 5 6 2020-02-09 6 7 2020-02-16 7 8 2020-02-23 8 9 2020-03-01 9 10 2020-03-08 after truncate: Id time_series 1 2 2020-01-12
解決方案
為了解決這個問題,我們將遵循以下步驟:
定義一個數據框。
在 start=’01/01/2020’, periods = 10 中建立 date_range 函式並將 freq = ‘W’ 賦予它。它將生成從給定的開始日期到下一個周開始日期的十個日期,並將其儲存為 df[‘time_series’]。
df['time_series'] = pd.date_range('01/01/2020',
periods=10,
freq='W')在一些索引值內應用 df.truncate() 函式,如 before=’01/01/2020’, after=’10/02/2020’,並將其儲存為 result,
result = df.truncate(before='01/01/2020',after='10/02/2020')
示例
讓我們瞭解一下下面的實施,以獲得更好的理解:
import pandas as pd
d = {'Id': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(d)
df['time_series'] = pd.date_range('01/01/2020',
periods=10,
freq='W')
print(df)
result = df.truncate(before='01/01/2020',after='10/02/2020')
print(result)輸出
before truncate: Id time_series 0 1 2020-01-05 1 2 2020-01-12 2 3 2020-01-19 3 4 2020-01-26 4 5 2020-02-02 5 6 2020-02-09 6 7 2020-02-16 7 8 2020-02-23 8 9 2020-03-01 9 10 2020-03-08 after truncate: Id time_series 1 2 2020-01-12
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP