将天数 Int64 转换为日期

Convert Days Int64 to Date

我需要将以下数据框(天)转换为物理日期。当 (days=0) 这是基准年 01/01/1960。您能否协助将天数列(从 1960 年 1 月 1 日开始的天数)转换回日期?

df=pd.DataFrame([-730,-640,-549,457,-365,275,-184,-92,0,91,182,274,366],columns=['days'])
df['base_year']=datetime.date(1960,1,1)

回想起来,MaxU的回答更好。以下内容可能对旧 Pandas 版本有用。

有几种方法可以做到这一点。一种是使用 datetime.timedelta 和列表理解:

from datetime import timedelta
import pandas as pd

>>> [pd.to_datetime('01/01/1960') + timedelta(d) for d in [-730,-640,-549,457,-365,275,-184,-92,0,91,182,274,366]]
[Timestamp('1958-01-01 00:00:00'),
 Timestamp('1958-04-01 00:00:00'),
 Timestamp('1958-07-01 00:00:00'),
 Timestamp('1961-04-02 00:00:00'),
 Timestamp('1959-01-01 00:00:00'),
 Timestamp('1960-10-02 00:00:00'),
 Timestamp('1959-07-01 00:00:00'),
 Timestamp('1959-10-01 00:00:00'),
 Timestamp('1960-01-01 00:00:00'),
 Timestamp('1960-04-01 00:00:00'),
 Timestamp('1960-07-01 00:00:00'),
 Timestamp('1960-10-01 00:00:00'),
 Timestamp('1961-01-01 00:00:00')]

所以你可以使用

>>> DataFrame([pd.to_datetime('01/01/1960') + timedelta(d) for d in [-730,-640,-549,457,-365,275,-184,-92,0,91,182,274,366]],columns=['days'])
    days
0   1958-01-01
1   1958-04-01
2   1958-07-01
3   1961-04-02
4   1959-01-01
5   1960-10-02
6   1959-07-01
7   1959-10-01
8   1960-01-01
9   1960-04-01
10  1960-07-01
11  1960-10-01
12  1961-01-01

您可以使用相对较新的功能(在 Pandas 0.20.0 中添加)- origin of pd.to_datetime():

In [44]: df['date'] = pd.to_datetime(df['days'], origin='1960-01-01', unit='D')

In [45]: df
Out[45]:
    days       date
0   -730 1958-01-01
1   -640 1958-04-01
2   -549 1958-07-01
3    457 1961-04-02
4   -365 1959-01-01
5    275 1960-10-02
6   -184 1959-07-01
7    -92 1959-10-01
8      0 1960-01-01
9     91 1960-04-01
10   182 1960-07-01
11   274 1960-10-01
12   366 1961-01-01

来自docs

origin : scalar, default is ‘unix’

Define the reference date. The numeric values would be parsed as number of units (defined by unit) since this reference date.

If ‘unix’ (or POSIX) time; origin is set to 1970-01-01. If ‘julian’, unit must be ‘D’, and origin is set to beginning of Julian Calendar.

Julian day number 0 is assigned to the day starting at noon on January

1, 4713 BC. If Timestamp convertible, origin is set to Timestamp identified by origin.