Python 熊猫:asfreq与timeseries的奇怪行为
我正在尝试在不更改值的情况下将每月时间序列转换为年度比例Python 熊猫:asfreq与timeseries的奇怪行为,python,pandas,time-series,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 然后我将date列转换为datetime格式,并将其
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
然后我将date列转换为datetime格式,并将其设置为索引:
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()
之前,需要先对索引进行排序
尝试:
或者:使用resample()
在年初使用freq='AS'
EDIT1:
您还可以使用.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
我想使用原始的每月值。例如,第一个月的值(上个月也可以)。重采样正在处理此数据,但它应用了某种函数,如mean()或sum()。我只是想“过滤”数据……你能更具体地说“我只是想”过滤“数据”吗。你能举一个你想做什么的例子吗?请原谅我的无知,什么是(Frq=‘a’)假设?@ PrimPixy你可以考虑GROPBY的输出作为正确结果的一个例子。这就是我想要的。但是我不明白为什么。asfreq没有显示相同的数据。谢谢你的建议。但是,在对所有数据进行排序后,都有NaN值…df.resample('A')。asfreq()也给出了NaN值
freq='A'
将使用一年的最后一天,而freq='AS'
将使用一年的第一天。如果df中有一年中第一天或最后一天的数据,则将根据freq
值返回数据。在df.set\u index
之后的df['date']
列中有什么内容?请参阅EDIT1-希望它对Hanks有很大帮助!这是freq='AS'isntead'A',因为原始数据具有月份的第一个日期的值。
df = df.sort_index().asfreq(freq='A')
df = df.resample('A').asfreq()
df = df.resample('AS').agg('sum')
value
date
2017-01-01 3.0018
2018-01-01 2.0018
2019-01-01 1.0018