Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将timedelta64[ns]转换为十进制_Python_Pandas - Fatal编程技术网

Python 将timedelta64[ns]转换为十进制

Python 将timedelta64[ns]转换为十进制,python,pandas,Python,Pandas,我有一个数据框,用来计算blockTime列,即endDate和startDate之间的差值。它给出的结果类似于0天01:45:00,但我只需要几个小时的小数。在本例中为1.75 我的意见如下: import pandas as pd data = {'endDate': ['01/10/2020 15:23', '01/10/2020 16:31', '01/10/2020 16:20', '01/10/2020 11:00'], 'startDate': ['01/10/202

我有一个数据框,用来计算blockTime列,即endDate和startDate之间的差值。它给出的结果类似于0天01:45:00,但我只需要几个小时的小数。在本例中为1.75

我的意见如下:

import pandas as pd

data = {'endDate': ['01/10/2020 15:23', '01/10/2020 16:31', '01/10/2020 16:20', '01/10/2020 11:00'],
      'startDate': ['01/10/2020 13:38', '01/10/2020 14:49', '01/10/2020 14:30','01/10/2020 14:30']
      }

df = pd.DataFrame(data, columns = ['endDate','startDate'])

df['endDate'] = pd.to_datetime(df['endDate'])
df['startDate'] = pd.to_datetime(df['startDate'])

df['blockTime'] = (df['endDate'] - df['startDate'])

df = df.reindex(columns= ['startDate', 'endDate', 'blockTime'])
期望的结果将是一个如下所示的数据帧。注意,如果产生了负值,我需要以某种方式强调它是不正确的。我想-999可能是最理想的

startDate           endDate               blockTime                 desiredResult
2020-01-10 13:38:00 2020-01-10 15:23:00   0 days 01:45:00           1.75
2020-01-10 14:49:00 2020-01-10 16:31:00   0 days 01:42:00           1.70
2020-01-10 14:30:00 2020-01-10 16:20:00   0 days 01:50:00           1.83
2020-01-10 14:30:00 2020-01-10 11:00:00  -1 days +20:30:00          -999.00

这正是打印数据帧时表示
timedelta
对象的方式。如果您只想将小时数保存为一个
float
而不是整个
timedelta
对象,
timedelta
对象有一个
total_seconds()
函数,您可以这样使用:

def td2hours(tdobject):
    if tdobject.total_seconds() < 0:
        return -999
    return tdobject.total_seconds() / 3600

df['blockTime']= (df['endDate'] - df['startDate']).apply(td2hours)
输出:

              endDate           startDate   blockTime
0 2020-01-10 15:23:00 2020-01-10 13:38:00    1.750000
1 2020-01-10 16:31:00 2020-01-10 14:49:00    1.700000
2 2020-01-10 16:20:00 2020-01-10 14:30:00    1.833333
3 2020-01-10 11:00:00 2020-01-10 14:30:00 -999.000000

您可以使用
df['blockTime']=(df['endDate']-df['startDate']).dt.total_seconds()/3600
而不是使用
apply
              endDate           startDate   blockTime
0 2020-01-10 15:23:00 2020-01-10 13:38:00    1.750000
1 2020-01-10 16:31:00 2020-01-10 14:49:00    1.700000
2 2020-01-10 16:20:00 2020-01-10 14:30:00    1.833333
3 2020-01-10 11:00:00 2020-01-10 14:30:00 -999.000000