【问题标题】:calculate sunrise and sunset times from a datetime index using ephem in Python在 Python 中使用 ephe 从日期时间索引计算日出和日落时间
【发布时间】:2020-01-03 22:12:38
【问题描述】:

我有一个带有DateTime 索引的每日时间序列。我想在 DataFrame 中计算每天的日出和日落时间。结果将显示在riseset 列中。下面是我使用 pyephem 的脚本:

import ephem
import datetime

AliceS = ephem.Observer()
AliceS.lat = '-23.762'
AliceS.lon = '133.875'

AliceS.date = df.index

sun = ephem.Sun()

df['rise'] = ephem.localtime(AliceS.next_rising(sun))
df['set'] = ephem.localtime(AliceS.next_setting(sun))

这引发了

ValueError: dates must be initialized from a number, string, tuple, or datetime

我认为错误的原因是AliceS.date = df.index,但我不知道如何解决。

以下是日期时间索引的示例:

DateTime
2016-04-02
2016-04-03
2016-04-04
2016-04-07
2016-04-08

【问题讨论】:

    标签: python datetime pyephem


    【解决方案1】:

    来自docs的首页:

    PyEphem 不与 NumPy 互操作,因此在现代 IPython Notebook 中使用起来很尴尬。

    这基本上意味着next_rising and next_setting 方法只能对标量进行操作。快速而肮脏的解决方案是编写一个循环来将索引的每个元素转换为兼容的格式并以这种方式计算值:

    import ephem
    import datetime
    
    AliceS = ephem.Observer()
    AliceS.lat = '-23.762'
    AliceS.lon = '133.875'
    
    sun = ephem.Sun()
    
    def get_time(obs, obj, func):
        func = getattr(obs, func)
        def inner(date)
            obs.date = date
            return ephem.localtime(func(obj))
        return inner
    
    df['rise'] = pd.Series(df.index).apply(get_time(AliceS, sun, 'next_rising'))
    df['set'] = pd.Series(df.index).apply(get_time(AliceS, sun, 'next_setting'))
    

    不要让紧凑 (-ish) 符号欺骗您,apply 仍然只是一个 for 循环。

    更好的解决方案是遵循docs 中的建议:

    如果您的新项目可以这样做,我建议使用 Skyfield 而不是 PyEphem! (此时唯一缺少的是根据凯尔珀轨道元素预测彗星和小行星的位置。)

    这是Skyfield 的链接。可以通过pypiGitHub等普通渠道获得。

    【讨论】:

    • 物理学家。感谢您介绍 Skyfield,我从中获得了解决问题的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2016-12-23
    • 2010-10-16
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多