我想用当前时间戳之间的时间差填充dataframe列 以及分别为“类型A”或“非类型A”的最近时间戳,即类型A=1或类型A=0。 下面是一个小例子:
import numpy as np
import pandas as pd
from datetime import datetime
df = pd.DataFrame({'id':[1,2,3,4],
'tmstmp':[datetime(2018,5,4,13,27,10), datetime(2018,5,3,13,27,10),
datetime(2018,5,2,13,27,10), datetime(2018,5,1,13,27,10)],
'type_A':[0, 1, 0, 1],
'dt_A': [np.nan]*4,
'dt_notA': [np.nan]*4
})
(A行和非A行不一定交替,但时间戳列是 已按降序排序)。 我通过使用该整数索引和列名对整数行索引和access元素进行迭代,分别计算当前行和类型为_A=1或类型为_A=0的下一行中的时间戳之间的时间差:
keys = {1: 'dt_A', 0: 'dt_notA'}
ridx = 0
while ridx + 1 < df.shape[0]:
ts1 = df.iloc[ridx]['tmstmp']
ts2 = df.iloc[ridx + 1]['tmstmp']
found = 0 if df.iloc[ridx + 1]['type_A'] == 0 else 1
key = keys[found]
df.loc[ridx, key] = (ts1 - ts2).total_seconds()/3600
complement = 1 - found
j = 2
while ridx + j < df.shape[0] and df.iloc[ridx + j]['type_A'] != complement:
j += 1
if ridx + j < df.shape[0]:
ts1 = df.iloc[ridx]['tmstmp']
ts2 = df.iloc[ridx + j]['tmstmp']
val = (ts1 - ts2).total_seconds()/3600
else:
val = np.nan
df.loc[ridx, keys[complement]] = val
ridx += 1
出于效率原因,“不鼓励”对数据帧进行迭代(请参见How to iterate over rows in a DataFrame in Pandas?) 而使用整数索引更不“pythonic”,所以我的问题是:在这种特殊情况下,是否有一个“better”(更高效、更pythonic) 迭代数据帧以完成给定任务的方法? 非常感谢您的建议和想法
编辑:小示例的输入和输出数据帧-列dt_A
包含当前行和下一行之间的时间增量,下一行具有type_A = 1
,dt_notA
包含最近行具有type_A = 0
的时间增量
input:
id tmstmp type_A dt_A dt_notA
0 1 2018-05-04 13:27:10 0 NaN NaN
1 2 2018-05-03 13:27:10 1 NaN NaN
2 3 2018-05-02 13:27:10 0 NaN NaN
3 4 2018-05-01 13:27:10 1 NaN NaN
输出:
id tmstmp type_A dt_A dt_notA
0 1 2018-05-04 13:27:10 0 24.0 48.0
1 2 2018-05-03 13:27:10 1 48.0 24.0
2 3 2018-05-02 13:27:10 0 24.0 NaN
3 4 2018-05-01 13:27:10 1 NaN NaN
通过以下方式应用这些功能:
然后
df
变成:相关问题 更多 >
编程相关推荐