python 在统一的半年期间重新采样(相当于 pandas resample 中的 'BQ')

标签 python pandas

python 中是否有等效于“BQ”的半年一次重采样?我没有在这里找到它

http://pandas.pydata.org/pandas-docs/dev/timeseries.html#up-and-downsampling

我有一组记录,其中一些遵循 jun-dec,一些遵循 jan-jul,一些遵循 feb-auh 等。我如何将所有这些重新采样到 jun-dec(并发用于 jun-dec,然后6 月/12 月是否有其他记录?

谢谢。

最佳答案

'2BQ' 怎么样?

In [57]: ts = pd.Series(range(1000), index=pd.date_range('2000-4-15', periods=1000))

In [58]: ts.resample('2BQ', how='sum')
Out[58]: 
2000-06-30      2926
2000-12-29     30485
2001-06-29     63609
2001-12-31     98605
2002-06-28    127985
2002-12-31    166935
2003-06-30      8955
Freq: 2BQ-DEC, dtype: int64

第 2 季度偏移量将基于系列中的第一个时间戳,因此如果您的数据恰好从 1 月至 3 月或 6 月至 9 月开始,则 anchor 将是错误的。解决它的一种方法是在系列的开头填充一个虚拟日期,这样 anchor 就正确了。

ts = pd.Series(range(1000), index=pd.date_range('2000-3-15', periods=1000))

from datetime import datetime
if ts.index[0].month in [1,2,3]:
    ts.loc[datetime(ts.index[0].year - 1, 12, 1)] = np.nan
elif ts.index[0].month in [7,8,9]:
    ts.loc[datetime(ts.index[0].year, 6, 1)] = np.nan

应该给出正确答案(并且可以删除第一个条目)。

In [85]: ts.resample('2BQ', how='sum')
Out[85]: 
1999-12-31       NaN
2000-06-30      5778
2000-12-29     36127
2001-06-29     69251
2001-12-31    104340
2002-06-28    133534
2002-12-31    150470
Freq: 2BQ-DEC, dtype: float64

关于python 在统一的半年期间重新采样(相当于 pandas resample 中的 'BQ'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25383397/

相关文章:

python - 如何渲染 svg 文件的*部分*?

python - 在 VBA 中,如何使用 Shell.Run 而不是 Shell.Exec 来捕获 shell 输出?

python - 尝试删除打印机时访问被拒绝

python - 使用 SQLAlchemy 查询到 Pandas DataFrame 时重命名列

python - 如何在 pandas 中将 n*m DataFrame 与 1*m DataFrame 相乘?

python - 如何按 Pandas 中的中值对箱线图进行排序

python - 尝试删除 Pandas 中的异常值时出现 ValueError

python - 如何对数字字符串的python列表进行排序

python - 相关热图在 Python 中将值转换为 nan

python - 如何将数据重新组织到 pandas 中的新数据框中,以这种方式显示数据的更改?