如何使用星体包将日落和日出数据的结果转换为数据帧



我正试图找到一种方法,将我在某个城市使用astral包计算某个时间间隔的黎明和黄昏时间得到的结果转换为数据帧。问题是,一旦我得到日出和日落信息的结果,我就很难将其转换为数据帧进行进一步分析。我的代码现在显示在下面

from astral import *
def get_astral_summary():
x=print((
f'Dawn:    {s["dawn"]}n'
f'Sunrise: {s["sunrise"]}n'
f'Noon:    {s["noon"]}n'
f'Sunset:  {s["sunset"]}n'
f'Dusk:    {s["dusk"]}n'
))
return x 
city = LocationInfo("Surrey", "Canada", 'US/Pacific',49.104599,-122.823509)
x =pd.date_range(start="2020-12-09",end="2020-12-11")
for y in x:
s = sun(city.observer, date=y)
get_astral_summary()

现在,我可以看到我的结果的方式是制作打印结果的函数,输出如下所示:

Dawn:    2020-12-09 15:16:48.899052+00:00
Sunrise: 2020-12-09 15:54:44.342273+00:00
Noon:    2020-12-09 20:03:37+00:00
Sunset:  2020-12-10 00:13:05.243283+00:00
Dusk:    2020-12-10 00:51:00.107776+00:00
Dawn:    2020-12-10 15:17:44.663065+00:00
Sunrise: 2020-12-10 15:55:43.641196+00:00
Noon:    2020-12-10 20:04:04+00:00
Sunset:  2020-12-11 00:13:01.662368+00:00
Dusk:    2020-12-11 00:51:00.111312+00:00
Dawn:    2020-12-11 15:18:38.380512+00:00
Sunrise: 2020-12-11 15:56:40.604162+00:00
Noon:    2020-12-11 20:04:32+00:00
Sunset:  2020-12-12 00:13:01.168222+00:00
Dusk:    2020-12-12 00:51:02.912291+00:00

问题来了:如何将其放入时间格式正确的数据帧中?我注意到,当我刚刚调用变量s时,数据类型看起来有点像字典,如下所示:

{'dawn': datetime.datetime(2020, 12, 11, 15, 18, 38, 380512, tzinfo=<UTC>),
'dusk': datetime.datetime(2020, 12, 12, 0, 51, 2, 912291, tzinfo=<UTC>),
'noon': datetime.datetime(2020, 12, 11, 20, 4, 32, tzinfo=<UTC>),
'sunrise': datetime.datetime(2020, 12, 11, 15, 56, 40, 604162, tzinfo=<UTC>),
'sunset': datetime.datetime(2020, 12, 12, 0, 13, 1, 168222, tzinfo=<UTC>)}

我在做时注意到了

df = pd.DataFrame([s], columns=s.keys())

数据帧没有给我整个时间间隔,它只给了我下面显示的

dawn  ...                             dusk
0 2020-12-15 15:21:51.681536+00:00  ... 2020-12-16 00:51:41.956146+00:00
[1 rows x 5 columns]

有人能给我一些解决这个问题的建议吗?谢谢

您可以使用来自x:的列表理解

pd.DataFrame([sun(city.observer, date=z) for z in x])

输出:

dawn              sunrise                 noon  
0 2020-12-09 15:16:... 2020-12-09 15:54:... 2020-12-09 20:03:...   
1 2020-12-10 15:17:... 2020-12-10 15:55:... 2020-12-10 20:04:...   
2 2020-12-11 15:18:... 2020-12-11 15:56:... 2020-12-11 20:04:...   
sunset                 dusk  
0 2020-12-10 00:13:... 2020-12-10 00:51:...  
1 2020-12-11 00:13:... 2020-12-11 00:51:...  
2 2020-12-12 00:13:... 2020-12-12 00:51:...  
  1. 像您所做的那样,为每个数据键创建一个具有列的数据帧:
df = pd.DataFrame(columns=s.keys())
  1. 循环并创建数据时,将数据附加到df:
for y in x:
s = sun(city.observer, date=y)
df = df.append(s, ignore_index=True)

注意:函数get_astral_summary()应该有s作为参数,而不是来自外部范围。

相关内容

  • 没有找到相关文章

最新更新