问题描述
我有一个熊猫数据框,其中有两列datetime64列和一列timedelta64列,这是两列之间的差异.我正在尝试绘制timedelta列的直方图,以可视化两个事件之间的时间差.
I have a pandas dataframe that has two datetime64 columns and one timedelta64 column that is the difference between the two columns. I'm trying to plot a histogram of the timedelta column to visualize the time differences between the two events.
但是,仅使用df['time_delta']
会导致:TypeError: ufunc add cannot use operands with types dtype('<m8[ns]') and dtype('float64')
However, just using df['time_delta']
results in: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]
Trying to convert the timedelta column to : float--> df2 = df1['time_delta'].astype(float)
results in:TypeError: cannot astype a timedelta from [timedelta64[ns]] to [float64]
如何创建熊猫timedelta数据的直方图?
How would one create a histogram of pandas timedelta data?
推荐答案
以下是转换时间增量的方法,文档是
Here are ways to convert timedeltas, docs are 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转换将舍入到该单位
Convert using astype will round to that unit
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
这篇关于绘制 pandas timedelta的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!