首页 > 解决方案 > 按月过滤 DataFrame

问题描述

我想应用这篇文章中描述的解决方案,但它对我不起作用。我收到以下错误:AttributeError: Can only use .dt accessor with datetimelike values

In [32]: df                                                                     
Out[32]: 
           DATE  MAX_TEMPERATURE_C  MIN_TEMPERATURE_C           OPINION
0    2019-01-01                  9                  4          very bad
1    2019-01-02                  8                  5          very bad
2    2019-01-03                  6                  0          very bad
3    2019-01-04                  5                 -1          very bad
4    2019-01-05                  6                 -1          very bad
..          ...                ...                ...               ...
360  2019-12-27                 13                 10  not good not bad
361  2019-12-28                 11                  5          very bad
362  2019-12-29                  9                  2          very bad
363  2019-12-30                 12                  4          very bad
364  2019-12-31                 10                  4          very bad

[365 rows x 4 columns]

In [33]: df = df[df['DATE'].dt.month == 11]                                     
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-f625ecd088ca> in <module>
----> 1 df = df[df['DATE'].dt.month == 11]

~/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5268             or name in self._accessors
   5269         ):
-> 5270             return object.__getattribute__(self, name)
   5271         else:
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):

~/anaconda3/lib/python3.7/site-packages/pandas/core/accessor.py in __get__(self, obj, cls)
    185             # we're accessing the attribute of the class, i.e., Dataset.geo
    186             return self._accessor
--> 187         accessor_obj = self._accessor(obj)
    188         # Replace the property with the accessor object. Inspired by:
    189         # http://www.pydanny.com/cached-property.html

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/accessors.py in __new__(cls, data)
    336             return DatetimeProperties(data, orig)
    337 
--> 338         raise AttributeError("Can only use .dt accessor with datetimelike values")

AttributeError: Can only use .dt accessor with datetimelike values

任何人都可以帮忙吗?

标签: pythonpandasdataframe

解决方案


推荐阅读