我希望将DataFrame中的DatetimeIndex转换为浮点格式,以便在我的模型中进行分析。有人能告诉我该如何做吗? 我需要使用date2num()函数吗?非常感谢!
我希望将DataFrame中的DatetimeIndex转换为浮点格式,以便在我的模型中进行分析。有人能告诉我该如何做吗? 我需要使用date2num()函数吗?非常感谢!
将 Timedelta
转换并从 dt.total_seconds
中提取总秒数:
df
date
0 2013-01-01
1 2013-01-02
2 2013-01-03
3 2013-01-04
4 2013-01-05
5 2013-01-06
6 2013-01-07
7 2013-01-08
8 2013-01-09
9 2013-01-10
pd.to_timedelta(df.date).dt.total_seconds()
0 1.356998e+09
1 1.357085e+09
2 1.357171e+09
3 1.357258e+09
4 1.357344e+09
5 1.357430e+09
6 1.357517e+09
7 1.357603e+09
8 1.357690e+09
9 1.357776e+09
Name: date, dtype: float64
或者,也许将这些数据呈现为 int
类型会更有用:
pd.to_timedelta(df.date).dt.total_seconds().astype(int)
0 1356998400
1 1357084800
2 1357171200
3 1357257600
4 1357344000
5 1357430400
6 1357516800
7 1357603200
8 1357689600
9 1357776000
Name: date, dtype: int64
请使用astype float,即使您有像以下这样的数据框
df = pd.DataFrame({'date': ['1998-03-01 00:00:01', '2001-04-01 00:00:01','1998-06-01 00:00:01','2001-08-01 00:00:01','2001-05-03 00:00:01','1994-03-01 00:00:01'] })
df['date'] = pd.to_datetime(df['date'])
df['x'] = list('abcdef')
df = df.set_index('date')
然后
df.index.values.astype(float)
array([ 8.88710401e+17, 9.86083201e+17, 8.96659201e+17,
9.96624001e+17, 9.88848001e+17, 7.62480001e+17])
pd.to_datetime(df.index.values.astype(float))
DatetimeIndex(['1998-03-01 00:00:01', '2001-04-01 00:00:01',
'1998-06-01 00:00:01', '2001-08-01 00:00:01',
'2001-05-03 00:00:01', '1994-03-01 00:00:01'],
dtype='datetime64[ns]', freq=None)
df['date'].values.astype(float)
将给出与您得到的相同答案,但是以18次幂的形式。 - Bharath M Shetty我找到了另一个解决方案:
df['date'] = df['date'].astype('datetime64').astype(int).astype(float)
df['date'].astype(int).astype(float)
- Tomek Tajnedatetime.date
对象,则直接转换为浮点数将失败。日期对象可以转换为datetime64
以获得所需的数字表示分辨率,但这些对象可能无法转换为浮点值,因此需要先进行转换为整数的中间步骤。 - Rob Hallastype(int)
会引发警告,建议使用 .view(int)
:flatten_df['first_year_date'].astype('datetime64').view(int).astype(float)
。 - Dr Fabio Gori我认为这提供了另一种解决方案,假设一个带有DatetimeIndex的数据框。
pd.to_numeric(df.index, downcast='float')
# although normally I would prefer an integer, and to coerce errors to NaN
pd.to_numeric(df.index, errors = 'coerce',downcast='integer')
DateTimeIndex
的特定部分,请尝试以下方法:ADDITIONAL = 1
ddf_c['ts_part_numeric'] = ((ddf_c.index.dt.year * (10000 * ADDITIONAL)) + (ddf_c.index.dt.month * (100 * ADDITIONAL)) + ((ddf_c.index.dt.day) * ADDITIONAL))
20190523
20190524
可以根据您所需的时间分辨率进行调整。
pd.to_datetime(pd.to_timedelta(df.date).dt.total_seconds().values[0])
。它会给出1970年的结果... - Bharath M Shetty