Python 時系列分析 1,000本ノック
– ノック4: 時系列データのシフト –

Python 時系列分析 1,000本ノック– ノック4: 時系列データのシフト –

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

Python コード:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import pandas as pd
df = pd.DataFrame(
{'A': [1, 2, 3, 4]},
index=pd.to_datetime([
'2023-01-01',
'2023-01-02',
'2023-01-03',
'2023-01-04'
])
)
print(df.shift(1))
import pandas as pd df = pd.DataFrame( {'A': [1, 2, 3, 4]}, index=pd.to_datetime([ '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04' ]) ) print(df.shift(1))
import pandas as pd

df = pd.DataFrame(
    {'A': [1, 2, 3, 4]}, 
    index=pd.to_datetime([
        '2023-01-01',
        '2023-01-02',
        '2023-01-03', 
        '2023-01-04'
        ])
    )

print(df.shift(1))

 

回答の選択肢:

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

 

出力例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
A
2023-01-01 NaN
2023-01-02 1.0
2023-01-03 2.0
2023-01-04 3.0
A 2023-01-01 NaN 2023-01-02 1.0 2023-01-03 2.0 2023-01-04 3.0
              A
2023-01-01  NaN
2023-01-02  1.0
2023-01-03  2.0
2023-01-04  3.0

 

正解:

B

 

解説:

このコードは、日付をインデックスとする pandas DataFrame を作成し、shift(1)を使用してデータを1期分ずらします。これにより、各データポイントが1日後の日付に移動し、最初の日付にはNaNが表示されます。