0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

resampleの引数のconvention="end"はどこを指しているのか

Last updated at Posted at 2023-04-01

今回の疑問

期間でインデックス付けされたデータをアップサンプリングする際、resample(...convention="end")の"end"が何を対象にしているかわからないので調べてみました。

import pandas as pd
frame = pd.Series([1,2],index=pd.period_range("2022","2023",freq="A"))

#2022	1
#2023	2

frame.resample("Q",convention="start").asfreq()

#2022Q1	1.0
#2022Q2	NaN
#2022Q3	NaN
#2022Q4	NaN
#2023Q1	2.0
#2023Q2	NaN
#2023Q3	NaN
#2023Q4	NaN
#ここまでは理解可能。

frame.resample("Q",convention="end").asfreq()

#2022Q4	1.0
#2023Q1	NaN
#2023Q2	NaN
#2023Q3	NaN
#2023Q4	2.0
#???
#2022Q1~2022Q3まで消えた。

調べたこと

まず初めに公式を見なさいと偉い人が言ってました。
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html

convention{‘start’, ‘end’, ‘s’, ‘e’}, default ‘start’
For PeriodIndex only, controls whether to use the start or end of rule.

こちらによるとデフォルトは"start"で、PeriodIndexにしか使えず、ルール(第一引数のデータセット)の始まりか終わりを選べるそうです。

. . .?

これで理解ができれば苦労していないです。

手を動かして理解していきましょう。
別のデータを用意して傾向をつかんでいきます。

qframe = pd.Series([1,2,3,4],index=pd.period_range("2023",periods=4,freq="Q",))

#2023Q1    1
#2023Q2    2
#2023Q3    3
#2023Q4    4

qframe.resample("M",convention="start").asfreq()

#2023-01    1.0
#2023-02    NaN
#2023-03    NaN
#2023-04    2.0
#2023-05    NaN
#2023-06    NaN
#2023-07    3.0
#2023-08    NaN
#2023-09    NaN
#2023-10    4.0
#2023-11    NaN
#2023-12    NaN

qframe.resample("M",convention="end").asfreq()

#2023-03    1.0
#2023-04    NaN
#2023-05    NaN
#2023-06    2.0
#2023-07    NaN
#2023-08    NaN
#2023-09    3.0
#2023-10    NaN
#2023-11    NaN
#2023-12    4.0
#2023-01と2023-02が消えた。

変化をまとめてみます。


#1つめ
#2022 1 
convention="start"
2022Q1    1.0
2022Q2    NaN
2022Q3    NaN
2022Q4    NaN
convention="end"
2022Q4    1.0

#2つめ
#2023Q1    1
convention="start"
2023-01    1.0
2023-02    NaN
2023-03    NaN
convention="end"
2023-03    1.0

まとめ

2つのシリーズの再サンプリングの共通点は1つめの期間のインデックスに対して作用が働いているようです。

convention="start"の場合は1つ目の期間の最初。
convention="end"の場合は1つ目の期間の最後。

を対象にしていることがわかりました。

おわり。

参考にさせていただいたもの
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html
https://runebook.dev/ja/docs/pandas/reference/api/pandas.dataframe.resample

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?