python-3.x - 从日期时间索引输出唯一年份集

标签 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)>

欢迎任何建议。

最佳答案

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

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/

相关文章:

python - Pandas 根据行中其他单元格的值为单元格赋值

python - 导入模块不起作用

python - 在 Python 中使用频率列表创建列表

python - 从 pandas 大数据集中获取犯罪 'count'

python - 从具有相同索引和列的两个 pandas 数据帧执行计算的最快方法

python - 在具有多个具有不同值的日期时间列的 DataFrame 中设置日期时间索引

Python 机器人错误消息

python - pandas如何识别具有特定模式的字符串

python - pip3 install Flask-MongoEngine 安装失败

python - Pandas:如果在 groupby 之后基于其他列存在重复项,则根据特定列上给出的权重保留特定行