与Pandas套餐对接#
这个 astropy.timeseries
package is not the only package to provide functionality related to time series. Another notable package is pandas ,它提供了 pandas.DataFrame
上课。主要好处是 astropy.timeseries
在天文学研究方面,有以下几点:
时间列是
Time
对象,该对象支持非常高精度的时间表示,并使在不同的时间刻度和格式(例如,ISO 8601时间戳、朱利安日期等)之间进行转换非常容易。数据列可以包括
Quantity
带单位的对象。这个
BinnedTimeSeries
类包括可变宽度的时间容器。有针对常见时间序列文件格式的内置读卡器,以及定义自定义读写器的功能。
然而,也有使用Pandas的案例 DataFrame
对象可能有意义,因此我们提供了转换为/来自的方法 DataFrame
物体。
例子#
考虑一个从 DataFrame
:
>>> import pandas
>>> import numpy as np
>>> from astropy.utils.introspection import minversion
>>> df = pandas.DataFrame()
>>> df['a'] = [1, 2, 3]
>>> times = np.array(['2015-07-04', '2015-07-05', '2015-07-06'], dtype=np.datetime64)
>>> df.set_index(pandas.DatetimeIndex(times), inplace=True)
>>> df
a
2015-07-04 1
2015-07-05 2
2015-07-06 3
We can convert this to an astropy
TimeSeries
using
from_pandas()
:
>>> from astropy.timeseries import TimeSeries
>>> ts = TimeSeries.from_pandas(df)
>>> ts
<TimeSeries length=3>
time a
Time int64
----------------------------- -----
2015-07-04T00:00:00.000000000 1
2015-07-05T00:00:00.000000000 2
2015-07-06T00:00:00.000000000 3
正在转换为 DataFrame
也可以用 to_pandas()
:
>>> ts['b'] = [1.2, 3.4, 5.4]
>>> df_new = ts.to_pandas()
>>> df_new
a b
time
2015-07-04 1 1.2
2015-07-05 2 3.4
2015-07-06 3 5.4
支持time列中缺少的值,并将其正确转换为pandas的NaT对象:
>>> ts.time[2] = np.nan
>>> ts
<TimeSeries length=3>
time a b
Time int64 float64
----------------------------- ----- -------
2015-07-04T00:00:00.000000000 1 1.2
2015-07-05T00:00:00.000000000 2 3.4
——— 3 5.4
>>> df_missing = ts.to_pandas()
>>> df_missing
a b
time
2015-07-04 1 1.2
2015-07-05 2 3.4
NaT 3 5.4