在Python中使用ephem从datetime索引计算日出和日落时间

2024-05-16 00:50:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有DateTime索引的每日时间序列。我想计算数据帧中每天的日出和日落时间。结果将显示在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索引的示例:

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

Tags: importdfdatetimedateindex时间序列next
1条回答
网友
1楼 · 发布于 2024-05-16 00:50:13

docs的首页:

PyEphem does not interoperate with NumPy and so is awkward to use in a modern IPython Notebook.

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

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)符号欺骗你,^{}仍然只是一个for循环。你知道吗

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

I recommend using Skyfield instead of PyEphem if it’s possible for your new project to do so! (The only thing missing at this point is predicting positions from Kelperian orbital elements for comets and asteroids.)

这里是到Skyfield的链接。它可以通过pypiGitHub等正常通道获得。你知道吗

相关问题 更多 >