我有以下创建为df
的示例数据框:
import numpy as np
import pandas as pd
now = pd.datetime.now().replace(microsecond=0)
dates = pd.date_range(now, periods = 30*60*60, freq='S')
N=15
df = pd.DataFrame({'id':range(1, N+1, 1), 'stime': np.random.choice(dates, size=N), 'etime': np.random.choice(dates, size=N), 'mult':np.random.rand(N)})
df.loc[:,'duration'] = df['etime'] - df['stime']
df
etime id mult stime duration
0 2018-05-10 11:51:41 1 0.566939 2018-05-09 23:35:27 0 days 12:16:14
1 2018-05-09 22:38:13 2 0.403033 2018-05-09 15:49:24 0 days 06:48:49
2 2018-05-09 18:24:55 3 0.758680 2018-05-09 20:22:22 -1 days +22:02:33
3 2018-05-09 10:08:12 4 0.829369 2018-05-10 14:08:13 -2 days +19:59:59
4 2018-05-10 04:32:41 5 0.314382 2018-05-10 12:50:18 -1 days +15:42:23
5 2018-05-09 15:02:06 6 0.473411 2018-05-09 20:27:24 -1 days +18:34:42
6 2018-05-09 22:25:43 7 0.367398 2018-05-09 12:31:41 0 days 09:54:02
7 2018-05-10 05:30:56 8 0.591833 2018-05-09 21:13:55 0 days 08:17:01
8 2018-05-09 23:49:05 9 0.080266 2018-05-10 12:40:43 -1 days +11:08:22
9 2018-05-10 13:24:00 10 0.523454 2018-05-10 06:04:01 0 days 07:19:59
10 2018-05-10 14:35:25 11 0.392015 2018-05-10 13:03:00 0 days 01:32:25
11 2018-05-10 11:23:48 12 0.178010 2018-05-10 12:48:52 -1 days +22:34:56
12 2018-05-10 03:31:42 13 0.582963 2018-05-10 12:14:24 -1 days +15:17:18
13 2018-05-09 12:03:18 14 0.499407 2018-05-10 11:13:47 -1 days +00:49:31
14 2018-05-09 15:56:17 15 0.527276 2018-05-09 13:16:18 0 days 02:39:59
我希望获得以下列,但正在抛出TypeError: incompatible type [float64] for a datetime/timedelta operation
:
df.loc[:, 'wwx'] = df['duration']*df['mult']*df['mult']
df.loc[:, 'wx'] = df['duration']*df['mult']
非常感谢任何帮助。
答案 0 :(得分:1)
将它转换为时间戳差异可能更容易,然后再返回。试试,例如:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
def main():
unittest.main()
if __name__ == '__main__':
main()