Pandas filter dataframe rows with a specific year

前端 未结 2 981
时光取名叫无心
时光取名叫无心 2020-12-01 08:15

I have a dataframe df and it has a Date column. I want to create two new data frames. One which contains all of the rows from df where

相关标签:
2条回答
  • 2020-12-01 08:50

    You can use datetime accesor.

    import datetime as dt
    df['Date'] = pd.to_datetime(df['Date'])
    
    include = df[df['Date'].dt.year == year]
    exclude = df[df['Date'].dt.year != year]
    
    0 讨论(0)
  • 2020-12-01 08:56

    You can simplify it by inverting mask by ~ and for condition use Series.dt.year with int for cast string year:

    mask = df['Date'].dt.year == int(year)
    include = df[mask]
    exclude = df[~mask]
    
    0 讨论(0)
提交回复
热议问题