将pandas DateOffset转换为微秒

时间:2015-07-10 14:38:26

标签: python datetime pandas dataframe

我想检索数据帧的采样频率,以微秒为单位的整数,或以秒为单位的浮点数。

我发现以下内容正常工作

import pandas as pd
(pd.datetime(1,1,1) + data_frame.index.freq - pd.datetime(1,1,1)).total_seconds()

但不知何故,我认为可能有一种不那么麻烦的方式......

1 个答案:

答案 0 :(得分:1)

您可能想要使用pd.Timedelta

import pandas as pd
import numpy as np

# your dataframe with some unknown freq
# ====================================
df = pd.DataFrame(np.random.randn(100), columns=['col'], index=pd.date_range('2015-01-01 00:00:00', periods=100, freq='20ms'))

Out[263]: 
                            col
2015-01-01 00:00:00.000  0.8647
2015-01-01 00:00:00.020 -0.2269
2015-01-01 00:00:00.040  0.8112
2015-01-01 00:00:00.060  0.2878
2015-01-01 00:00:00.080 -0.5385
2015-01-01 00:00:00.100  1.9085
2015-01-01 00:00:00.120 -0.4758
2015-01-01 00:00:00.140  1.4407
2015-01-01 00:00:00.160 -1.1491
2015-01-01 00:00:00.180  0.8057
...                         ...
2015-01-01 00:00:01.800 -0.6615
2015-01-01 00:00:01.820  0.7059
2015-01-01 00:00:01.840 -0.3586
2015-01-01 00:00:01.860  0.7320
2015-01-01 00:00:01.880 -0.0364
2015-01-01 00:00:01.900  0.5889
2015-01-01 00:00:01.920 -0.7796
2015-01-01 00:00:01.940  0.4763
2015-01-01 00:00:01.960  0.8339
2015-01-01 00:00:01.980  1.3138

[100 rows x 1 columns]


# processing using pd.Timedelta()
# =================================
# get the freq in ms
(df.index[1] - df.index[0])/pd.Timedelta('1ms')

Out[262]: 20.0