【发布时间】:2021-02-24 13:20:44
【问题描述】:
我需要遍历一个由 UNIX 时间戳索引的 DataFrame,并在一个列中,在将来的特定索引时间从不同行的另一列中分配一个值。这就是我目前正在做的事情:
df = pd.DataFrame([
[1523937600, 100.0, 0.0],
[1523937660, 120.0, 0.0],
[1523937720, 110.0, 0.0],
[1523937780, 90.0, 0.0],
[1523937840, 99.0, 0.0]],
columns=['time', 'value', 'target'])
df.set_index('time', inplace=True)
skip = 2 # mins skip-ahead
for i in range(0, df.shape[0]-1):
t = df.index[i] + (60*skip)
try:
df.iloc[i].target = df.loc[t].value
except KeyError:
df.iloc[i].target = 0.0
输出:
value target
time
1523937600 100.0 110.0
1523937660 120.0 90.0
1523937720 110.0 99.0
1523937780 90.0 0.0
1523937840 99.0 0.0
这可行,但我正在处理包含数百万行的数据集,并且需要很长时间。有没有更优化的方法来做到这一点?
编辑:添加示例输入/输出。请注意,重要的是我从具有计算索引时间的行中获取值,而不是仅仅向前看 n 行,因为时间之间可能存在间隙,或者两者之间可能存在额外的时间。
【问题讨论】:
-
请提供示例输入和预期输出以制作minimal reproducible example,以便我们更好地了解您的问题。见How to make good pandas examples
-
@G.Anderson 添加了示例输入/输出,谢谢。