【问题标题】:Python: slice yearly data between February and June with pandasPython:使用 pandas 对 2 月至 6 月之间的年度数据进行切片
【发布时间】:2022-01-26 15:12:10
【问题描述】:

我有一个数据集,其中包含从 2000 年到 2010 年的 10 年数据。我的初始日期时间为 2000 年 1 月 1 日,数据重新采样为每日。我还有一个每周计数器,当我应用slice() 函数时,我只会要求第 5 周到第 21 周(2 月 1 日到 5 月 30 日)。

我有点不知道如何每年对它进行切片,它是否涉及循环,或者 python 中是否有一个时间序列函数会知道每年对特定时期进行切片?下面是我到目前为止的代码,我有一个 for 循环应该是 slice(5, 21),但它不起作用。

我有什么建议可以让它工作吗?

import pandas as pd
from datetime import datetime, timedelta 

initial_datetime = pd.to_datetime("2000-01-01")

# Read the file
df = pd.read_csv("D:/tseries.csv")

# Convert seconds to datetime
df["Time"] = df["Time"].map(lambda dt: initial_datetime+timedelta(seconds=dt))
    
df = df.set_index(pd.DatetimeIndex(df["Time"]))
resampling_period = "24H"
df = df.resample(resampling_period).mean().interpolate()
df["Week"] = df.index.map(lambda dt: dt.week)
print(df)

【问题讨论】:

    标签: python pandas datetime time-series slice


    【解决方案1】:

    你可以使用loc进行切片:

    df.loc[df.Week.isin(range(5,22))]

    如果您想每年单独计算(例如平均值),您可以使用groupby

    subset = df.loc[df.Week.isin(range(5,22))]
    subset.groupby(subset.index.year).mean()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-07
      • 2016-11-04
      • 2019-04-17
      • 2017-04-06
      • 2019-10-07
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      相关资源
      最近更新 更多