绘制大熊猫timedelta

时间:2014-05-08 13:57:40

标签: python matplotlib pandas

我有一个pandas数据框,它有两个datetime64列和一个timedelta64列,它们是两列之间的差异。我试图绘制timedelta列的直方图,以显示两个事件之间的时间差异。

但是,仅使用df['time_delta']会导致: TypeError: ufunc add cannot use operands with types dtype('<m8[ns]') and dtype('float64')

尝试将timedelta列转换为:float--> df2 = df1['time_delta'].astype(float) 结果是: TypeError: cannot astype a timedelta from [timedelta64[ns]] to [float64]

如何创建pandas timedelta数据的直方图?

4 个答案:

答案 0 :(得分:39)

以下是转换timedeltas的方法,文档为here

In [2]: pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s')
Out[2]: 
0   0 days, 00:00:01
1   1 days, 00:00:01
2   2 days, 00:00:01
3   3 days, 00:00:01
4   4 days, 00:00:01
dtype: timedelta64[ns]

转换为秒(是精确转换)

In [3]: (pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s')).astype('timedelta64[s]')
Out[3]: 
0         1
1     86401
2    172801
3    259201
4    345601
dtype: float64

使用astype转换将转到该单位

In [4]: (pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s')).astype('timedelta64[D]')
Out[4]: 
0    0
1    1
2    2
3    3
4    4
dtype: float64

分部将提供准确的代表

In [5]: (pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s')) / np.timedelta64(1,'D')
Out[5]: 
0    0.000012
1    1.000012
2    2.000012
3    3.000012
4    4.000012
dtype: float64

答案 1 :(得分:3)

您可以使用numpy timedelta数据类型绘制漂亮的直方图。

例如:

try:
    if num[0] != " " and num[-1] != " ":
        num = float(num)
        is_float = True
except ValueError:
    is_float = False

将生成以秒为单位的时间增量的直方图。要使用分钟,您可以执行以下操作:

import binascii
import re
import collections
try:
    from itertools import izip as zip
except ImportError: # will be 3.x series
    pass
try:
    from itertools import islice as slice
except ImportError: # will be 3.x series
    pass
with open('path', 'rb') as f:
    for chunk in iter(lambda: f.read(), b''):
        s=binascii.hexlify(chunk)
        print(collections.Counter(zip(s),slice(s,1,None)))

The result should be like:Counter({(4d5a):200,(5a76):120,(7635):1000...}) but instead i am getting this error:


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-110-d99ed11a1260> in <module>
      3     for chunk in iter(lambda: f.read(), b''):
      4         s=binascii.hexlify(chunk)
----> 5         print(collections.Counter(zip(s),slice(s,1,None)))
      6 

~\Anaconda3\lib\collections\__init__.py in __init__(*args, **kwds)
    562         self, *args = args
    563         if len(args) > 1:
--> 564             raise TypeError('expected at most 1 arguments, got %d' % len(args))
    565         super(Counter, self).__init__()
    566         self.update(*args, **kwds)

TypeError: expected at most 1 arguments, got 2

或使用df['time_delta'].astype('timedelta64[s]').plot.hist() 时间增量。

(df['time_delta'].astype('timedelta64[s]') / 60).plot.hist()

以下是您可能需要的其他时间增量类型列表(来自the docs),具体取决于所需的分辨率:

[m]

答案 2 :(得分:3)

怎么样

df['time_delta'].dt.days.hist()

...? (根据需要/数据,您可以在secondsmicrosecondsnanoseconds而非days的位置使用)。

答案 3 :(得分:0)

另一种方法(对我有用)是简单地除以 Timedelta :

plt.hist(df['time_delta']/pd.Timedelta(minutes=1), bins=20)