我有一个TimeDelta列,其值看起来像这样:
2天21:54:00.000000000
我想要一个代表天数的小数,比如在这里是2 + 21/24 = 2.875(忽略分钟)。是否有简单的方法实现这一点?我看到有一个答案建议
res['Ecart_lacher_collecte'].apply(lambda x: float(x.item().days+x.item().hours/24.))
但我收到了“AttributeError:'str'对象没有属性'item'”错误。
Numpy版本为'1.10.4',Pandas版本为u'0.17.1'。
列最初是通过以下方式获取的:
lac['DateHeureLacher'] = pd.to_datetime(lac['Date lacher']+' '+lac['Heure lacher'],format='%d/%m/%Y %H:%M:%S')
cap['DateCollecte'] = pd.to_datetime(cap['Date de collecte']+' '+cap['Heure de collecte'],format='%d/%m/%Y %H:%M:%S')
在第一个脚本中编写。然后在第二个脚本中:
res = pd.merge(lac, cap, how='inner', on=['Loc'])
res['DateHeureLacher'] = pd.to_datetime(res['DateHeureLacher'],format='%Y-%m-%d %H:%M:%S')
res['DateCollecte'] = pd.to_datetime(res['DateCollecte'],format='%Y-%m-%d %H:%M:%S')
res['Ecart_lacher_collecte'] = res['DateCollecte'] - res['DateHeureLacher']
也许将其保存到csv文件会将它们的类型更改为字符串?我尝试进行的转换是在第三个脚本中完成的。
Sexe_x PiegeLacher latL longL Loc Col_x DateHeureLacher Nb envolees PiegeCapture latC longC Col_y Sexe_y Effectif DateCollecte DatePose Ecart_lacher_collecte Dist_m
M Q0-002 1629238 237877 H Rouge 2011-02-04 17:15:00 928 Q0-002 1629238 237877 Rouge M 1 2011-02-07 15:09:00 2011-02-07 12:14:00 2 days 21:54:00.000000000 0
M Q0-002 1629238 237877 H Rouge 2011-02-04 17:15:00 928 Q0-002 1629238 237877 Rouge M 4 2011-02-07 12:14:00 2011-02-07 09:42:00 2 days 18:59:00.000000000 0
M Q0-002 1629238 237877 H Rouge 2011-02-04 17:15:00 928 Q0-003 1629244 237950 Rouge M 1 2011-02-07 15:10:00 2011-02-07 12:16:00 2 days 21:55:00.000000000 75
res.info():
Sexe_x 922 non-null object
PiegeLacher 922 non-null object
latL 922 non-null int64
longL 922 non-null int64
Loc 922 non-null object
Col_x 922 non-null object
DateHeureLacher 922 non-null object
Nb envolees 922 non-null int64
PiegeCapture 922 non-null object
latC 922 non-null int64
longC 922 non-null int64
Col_y 922 non-null object
Sexe_y 922 non-null object
Effectif 922 non-null int64
DateCollecte 922 non-null object
DatePose 922 non-null object
Ecart_lacher_collecte 922 non-null object
Dist_m 922 non-null int64
res['columnname'].dt.total_seconds()/ (24 * 60 * 60)
。 - EdChumread_csv
中指定dtype以将其解析为timedelta64,所以你有几个选择。使用astype
将timedelta64转换为int64
,然后在读取时使用自定义转换器进行转换,或者在读取回来后可以用astype(np.timedelta64)
,这样也可以起作用。 - EdChum