我有一个日期时间索引如下,
>>> 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)>
欢迎任何建议。
最佳答案
你错过了()
,也有必要转换成列表:
L = temp.year.drop_duplicates().tolist()
L = list(temp.year.drop_duplicates())
另一种解决方案 unique
:
L = list(temp.year.unique())
print (L)
[2017, 2018]
关于python-3.x - 从日期时间索引输出唯一年份集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48297287/