按年份选择行

BER*_*ERA 6 python pandas

我想按一年选择行:

import pandas as pd
import numpy as np

df = pd.DataFrame(columns=['Start','End'],data=[[np.datetime64('2001-01-01'),np.datetime64('2001-07-01')],[np.datetime64('2002-01-01'),np.datetime64('2002-11-01')]])
print(df)

       Start        End
0 2001-01-01 2001-07-01
1 2002-01-01 2002-11-01
Run Code Online (Sandbox Code Playgroud)

所以我尝试:

df_2001 = df.loc[df['Start'.year == 2001)]]
Traceback (most recent call last):
  Python Shell, prompt 16, line 1
invalid syntax: <string>, line 1, pos 30
Run Code Online (Sandbox Code Playgroud)

如何在 datetime64 列中按年份进行选择?

jez*_*ael 7

使用dt.year

df_2001 = df[df['Start'].dt.year == 2001]
Run Code Online (Sandbox Code Playgroud)