我正在尝试创建一个数组,将分钟、秒和毫秒转换为秒,并连续添加它们。
我有一个时间戳如下的df:
Time Temp.
0 14:12:58:8230 135
1 14:12:59:0190 185
2 14:12:59:2150 138
我执行以下操作来检索数据并使用datetime.strptime
访问所有Timestamp列,并创建数组。但是,在运行它时,我似乎有一个KeyError : 0
。
elapsed_x = []
tmp_1 = []
for i in range (0, len(df)):
tmp = datetime.strptime(df.Time[i], '%H:%M:%S:%f')
tmp_ms = tmp.microsecond
tmp_s = tmp.second
tmp_min = tmp.minute
tmp_1.append(tmp_min*60 + tmp_s + tmp_ms/1000000)
for i in range (0, len(df)):
elapsed_x.append(tmp_1[i]-tmp_1[0])
我做错了什么?
panda可以以矢量化的方式处理时间戳:
tm = pd.to_datetime(df['Time'], format='%H:%M:%S:%f')
df['elapsed'] = (tm - tm.iloc[0]) / np.timedelta64(1,'s')
print(df['elapsed'])
给出:
0 0.000
1 0.196
2 0.392
Name: Time, dtype: float64
首先创建日期时间列,然后计算秒数和运行时间。
df['datetime'] = pd.to_datetime(df['Time'], format='%H:%M:%S:%f')
df['seconds'] = df.apply(lambda x : x['datetime'].hour*3600 + x['datetime'].minute*60 + x['datetime'].second + x['datetime'].microsecond/10**6, axis=1)
df['elapsed'] = df['seconds'] - df['seconds'].iloc[0]
输出:
Time Temp datetime seconds elapsed
0 14:12:58:8230 135 1900-01-01 14:12:58.823 51178.823 0.000
1 14:12:59:0190 185 1900-01-01 14:12:59.019 51179.019 0.196
2 14:12:59:2150 138 1900-01-01 14:12:59.215 51179.215 0.392