编写一个程序,根据索引值截断数据框的时间序列数据
pythonpandasserver side programmingprogramming更新于 2024/6/21 6:04:17
假设您有一个包含时间序列数据的数据框,截断数据的结果是,
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 = 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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

