Python 時系列分析 1,000本ノック
– ノック12: 時系列データの周期性分析 –

Python 時系列分析 1,000本ノック– ノック12: 時系列データの周期性分析 –

次の Python コードの出力はどれでしょうか?

Python コード:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import pandas as pd
import numpy as np
np.random.seed(2)
dates = pd.date_range(
'2023-01-01',
periods=12,
freq='M')
df = pd.DataFrame(
np.random.randn(12, 1),
index=dates,
columns=['A'])
print(df.diff(periods=4))
import pandas as pd import numpy as np np.random.seed(2) dates = pd.date_range( '2023-01-01', periods=12, freq='M') df = pd.DataFrame( np.random.randn(12, 1), index=dates, columns=['A']) print(df.diff(periods=4))
import pandas as pd
import numpy as np

np.random.seed(2)
dates = pd.date_range(
    '2023-01-01', 
    periods=12, 
    freq='M')
    
df = pd.DataFrame(
    np.random.randn(12, 1), 
    index=dates, 
    columns=['A'])

print(df.diff(periods=4))

 

回答の選択肢:

(A) 4ヶ月ごとの差分のランダムな値
(B) 各月のランダムな値
(C) すべてNaN
(D) 最初の4行がNaN、残りがランダムな値

 

出力例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
A
2023-01-31 NaN
2023-02-28 NaN
2023-03-31 NaN
2023-04-30 NaN
2023-05-31 -1.376678
2023-06-30 -0.785481
2023-07-31 2.639078
2023-08-31 -2.885559
2023-09-30 0.735483
2023-10-31 -0.067260
2023-11-30 0.048573
2023-12-31 3.537496
A 2023-01-31 NaN 2023-02-28 NaN 2023-03-31 NaN 2023-04-30 NaN 2023-05-31 -1.376678 2023-06-30 -0.785481 2023-07-31 2.639078 2023-08-31 -2.885559 2023-09-30 0.735483 2023-10-31 -0.067260 2023-11-30 0.048573 2023-12-31 3.537496
                   A
2023-01-31       NaN
2023-02-28       NaN
2023-03-31       NaN
2023-04-30       NaN
2023-05-31 -1.376678
2023-06-30 -0.785481
2023-07-31  2.639078
2023-08-31 -2.885559
2023-09-30  0.735483
2023-10-31 -0.067260
2023-11-30  0.048573
2023-12-31  3.537496

 

正解:

(D)

 

解説:

diff(periods=4) メソッドは、指定された期間(ここでは4ヶ月)前の値との差分を計算します。このコードでは、各月のデータに対して、4ヶ月前のデータとの差分を計算しています。最初の4ヶ月は比較する過去のデータが存在しないため、その値は NaN(非数)となります。5ヶ月目以降は、4ヶ月前の値との差分が計算され、ランダムに生成されたデータに基づく値が表示されます。

dfに格納されているデータは次のようになっています。ランダムな値を入れているため、人によって値は異なります。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
A
2023-01-31 -0.416758
2023-02-28 -0.056267
2023-03-31 -2.136196
2023-04-30 1.640271
2023-05-31 -1.793436
2023-06-30 -0.841747
2023-07-31 0.502881
2023-08-31 -1.245288
2023-09-30 -1.057952
2023-10-31 -0.909008
2023-11-30 0.551454
2023-12-31 2.292208
A 2023-01-31 -0.416758 2023-02-28 -0.056267 2023-03-31 -2.136196 2023-04-30 1.640271 2023-05-31 -1.793436 2023-06-30 -0.841747 2023-07-31 0.502881 2023-08-31 -1.245288 2023-09-30 -1.057952 2023-10-31 -0.909008 2023-11-30 0.551454 2023-12-31 2.292208
                   A
2023-01-31 -0.416758
2023-02-28 -0.056267
2023-03-31 -2.136196
2023-04-30  1.640271
2023-05-31 -1.793436
2023-06-30 -0.841747
2023-07-31  0.502881
2023-08-31 -1.245288
2023-09-30 -1.057952
2023-10-31 -0.909008
2023-11-30  0.551454
2023-12-31  2.292208