格式化datafram中的时间戳

2024-06-25 06:53:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表示电信号的大数据集(作为数组),它需要作为数据帧传递给另一个函数。问题是dataframe必须有一个带有freq属性的索引,并且原始数据集没有时间戳,1d数组和样本,但是我知道样本频率(86Hz),所以我可以为每个样本分配一个时间戳:

>>>a = [1,2,3,4,5,6]
>>>b = []
>>>j=0
>>>for i in a:
>>>    b.append(round(j, 3))
>>>    j = j+(1/86)
>>>c = np.c_[b, a]
     ([[ 0.   ,  1.   ],
       [ 0.012,  2.   ],
       [ 0.023,  3.   ],
       [ 0.035,  4.   ],
       [ 0.047,  5.   ],
       [ 0.058,  6.   ]])

然后我把它转换成一个数据帧:

d = pd.DataFrame(data=c[0:,1], index=c[0:,0])

        0
0.000   1.0
0.012   2.0
0.023   3.0
0.035   4.0
0.047   5.0
0.058   6.0

问题是索引没有freq属性,我认为这是一个格式问题,但不确定,在google搜索了一番之后,我什么也没找到。你知道吗

当我写的时候:

d.index.freq

它应该返回86,但是给我一个:

AttributeError: 'Float64Index' object has no attribute 'freq'

顺便说一下,时间戳以秒为单位,从第一个样本开始。。。或者这就是我的意图。你知道吗


Tags: 数据函数indataframefor原始数据index属性
1条回答
网友
1楼 · 发布于 2024-06-25 06:53:41

如果我理解正确,你可以这样做:

In [109]: d.index = pd.timedelta_range(d.index.min(), periods=len(d), freq='86L')

In [110]: d
Out[110]:
                   0
00:00:00         1.0
00:00:00.086000  2.0
00:00:00.172000  3.0
00:00:00.258000  4.0
00:00:00.344000  5.0
00:00:00.430000  6.0

In [111]: d.index.freq
Out[111]: <86 * Millis>

In [112]: d.index.dtype
Out[112]: dtype('<m8[ns]')

In [113]: d.index.dtype_str
Out[113]: 'timedelta64[ns]'

相关问题 更多 >