输出从datetime索引设置的唯一年份

时间:2018-01-17 09:08:28

标签: python-3.x pandas

我有一个日期时间索引,如下所示,

>>> temp
DatetimeIndex(['2017-01-03', '2017-01-04', '2017-01-05', '2017-01-06',
               '2017-01-09', '2017-01-10', '2017-01-11', '2017-01-12',
               '2017-01-13', '2017-01-16',
               ...
               '2017-12-27', '2017-12-28', '2017-12-29', '2018-01-02',
               '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-08',
               '2018-01-09', '2018-01-10'],
              dtype='datetime64[ns]', length=251, freq=None)
>>> temp.year
Int64Index([2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017,
            ...
            2017, 2017, 2017, 2018, 2018, 2018, 2018, 2018, 2018, 2018],
           dtype='int64', length=251)

我想输出唯一年份,例如列表[2017,2018]。 我已尝试过以下命令,但它没有按预期工作。

>>> temp.year.drop_duplicates
<bound method Index.drop_duplicates of Int64Index([2017, 2017, 2017, 2017, 2017,
 2017, 2017, 2017, 2017, 2017,
            ...
            2017, 2017, 2017, 2018, 2018, 2018, 2018, 2018, 2018, 2018],
           dtype='int64', length=251)>

任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:3)

你错过(),也有必要转换为列表:

L = temp.year.drop_duplicates().tolist()

L = list(temp.year.drop_duplicates())

unique的另一个解决方案:

L = list(temp.year.unique())

print (L)
[2017, 2018]

答案 1 :(得分:1)

我偏爱这个:

df.index.year.unique().values

返回:

<块引用>

[2017 2018]

或者,对于列表:

df.index.year.unique().to_list()

返回:

<块引用>

[2017、2018]