python - Pandas :asfreq 与时间序列的奇怪行为

标签 python pandas time-series

我正在尝试将每月时间序列转换为年度规模而不更改值。

import pandas as pd
df = pd.read_csv(url_inflation, delimiter='\t')
df.head()

    date    value
0   2019-09 -0.0016
1   2019-08 -0.0024
2   2019-07 0.0020
3   2019-06 0.0004
4   2019-05 0.0034

然后我将日期列转换为日期时间格式并将其设置为索引:

df['date'] = pd.to_datetime(df.date, yearfirst=True, format='%Y-%m')

df.set_index('date', inplace=True)

看起来索引是正确的:

df.info()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 345 entries, 2019-09-01 to 1991-01-01
Data columns (total 1 columns):
value    345 non-null float64
dtypes: float64(1)
memory usage: 5.4 KB

当我使用 asfreq 时,它会输出一个带有 DatetimeIndex 的空 DataFrame:

df.asfreq(freq='A')

date    value

df.asfreq(freq='A').info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 0 entries
Freq: A
Data columns (total 2 columns):
date     0 non-null object
value    0 non-null float64
dtypes: float64(1), object(1)
memory usage: 0.0+ bytes

使用 groupby 时似乎可以正常工作:

df1=df.groupby(pd.Grouper(level='date', freq='A')).nth(11)
df1.tail()

date        value
2014-12-31  0.0262
2015-12-31  0.0077
2016-12-31  0.0040
2017-12-31  0.0042
2018-12-31  0.0084

我错过了什么?

最佳答案

我认为在使用asfreq()之前您需要先对索引进行排序。

尝试:

df = df.sort_index().asfreq(freq='A')

或者:使用resample()

df = df.resample('A').asfreq()

使用freq='AS'作为年初。

编辑1:

您还可以使用 .agg().resample() 来获得预期结果。

df = df.resample('AS').agg('sum')

输出:

             value
date              
2017-01-01  3.0018
2018-01-01  2.0018
2019-01-01  1.0018

关于python - Pandas :asfreq 与时间序列的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59351967/

相关文章:

python - 使用python解压bz2文件有限制吗?

python - Azure 事件中心 python 库

python - 为什么Flask读取大文本文件不占内存?

python - Pandas dataframe.dot 划分方法

python - 转换 pandas 系列和日期时间对象

用于自动回归 (AR)、ARIMA、时间序列分析的 Java API

python - 如何根据条件用 NaN 替换数据框列值?

python - 比较两个 pandas Dataframe 的日期并在日期相似时添加值?

tensorflow - 用于时间序列异常检测的 Keras LSTM-VAE(变分自编码器)

Python 附加数据框,以便只有列保持不变