按年份过滤行

时间:2018-08-29 22:02:00

标签: python pandas csv datetime

我有这段代码,用于按年份过滤行。我知道您应该为该代码调用datetime方法。我在StackOverFlow上看到的每个答案都包含与我的相似的代码,并且适用于它们。如何打印2017-2018年的行值而不会出错?这是我的全部代码,我需要创建一个函数吗?我不熟悉日期时间代码,因此任何见解或指南都将非常有益,例如我说过过去两天一直在寻找答案而没有任何发现,因此我认为我做的是根本错误的事情。请让我知道是否需要进一步澄清我的问题。

import pandas as pd
import datetime


df = pd.read_csv('otd.csv', encoding='latin-1')
df['Delivery Date'] = pd.to_datetime(df['Delivery Date'], format= '%m/%d/%Y')
df[(df['Delivery Date'].year >= 2017) & (df['Delivery Date'].year <= 2018)]
print(df)

错误:

Traceback (most recent call last):
  File "C:\Users\khalha\eclipse-workspace\Test3\Project3\P3.py", line 10, in <module>
    df[(df['Delivery Date'].year >= 2017) & (df['Delivery Date'].year <= 2018)]
  File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\generic.py", line 4376, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'year'

otd.csv:

enter image description here

1 个答案:

答案 0 :(得分:1)

使用.dt访问器:dt

df[(df['Delivery Date'].dt.year >= 2017) & (df['Delivery Date'].dt.year <= 2018)]