Python 時系列分析 1,000本ノック
– ノック6: 時系列データの差分 –

Python 時系列分析 1,000本ノック– ノック6: 時系列データの差分 –

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

Python コード:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import pandas as pd
ts = pd.Series(
[1, 3, 6, 10, 15],
index=pd.date_range(
'2023-01-01',
periods=5
)
)
print(ts.diff())
import pandas as pd ts = pd.Series( [1, 3, 6, 10, 15], index=pd.date_range( '2023-01-01', periods=5 ) ) print(ts.diff())
import pandas as pd

ts = pd.Series(
    [1, 3, 6, 10, 15], 
    index=pd.date_range(
        '2023-01-01', 
        periods=5
        )
    )

print(ts.diff())

 

回答の選択肢:

A. 1, 2, 3, 4
B. 2, 3, 4, 5
C. NaN, 2, 3, 4, 5
D. NaN, 1, 2, 3, 4

 

出力例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
2023-01-01 NaN
2023-01-02 2.0
2023-01-03 3.0
2023-01-04 4.0
2023-01-05 5.0
Freq: D, dtype: float64
2023-01-01 NaN 2023-01-02 2.0 2023-01-03 3.0 2023-01-04 4.0 2023-01-05 5.0 Freq: D, dtype: float64
2023-01-01    NaN
2023-01-02    2.0
2023-01-03    3.0
2023-01-04    4.0
2023-01-05    5.0
Freq: D, dtype: float64

 

正解:

C

 

解説:

diff() 関数は、時系列データの各要素間の差分を計算します。最初の要素には比較する前の要素がないため、NaN(非数)が出力されます。残りの要素は、一つ前の要素との差分が計算されます。

ちなみに、tsに格納されているデータは次のようになっています。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
2023-01-01 1
2023-01-02 3
2023-01-03 6
2023-01-04 10
2023-01-05 15
Freq: D, dtype: int64
2023-01-01 1 2023-01-02 3 2023-01-03 6 2023-01-04 10 2023-01-05 15 Freq: D, dtype: int64
2023-01-01     1
2023-01-02     3
2023-01-03     6
2023-01-04    10
2023-01-05    15
Freq: D, dtype: int64