标题描述了我的情况。我已经有了这个的工作版本,但是当扩展到大型 DataFrame(>1M 行)时,它的效率非常低。我想知道是否有人有更好的主意这样做。
包含解决方案和代码的示例
创建一个新列next_time,该列具有下一个时间值,其中该price列大于当前行。
import pandas as pd
df = pd.DataFrame({'time': [15, 30, 45, 60, 75, 90], 'price': [10.00, 10.01, 10.00, 10.01, 10.02, 9.99]})
print(df)
time price
0 15 10.00
1 30 10.01
2 45 10.00
3 60 10.01
4 75 10.02
5 90 9.99
series_to_concat = []
for price in df['price'].unique():
index_equal_to_price = df[df['price'] == price].index
series_time_greater_than_price = df[df['price'] > price]['time']
time_greater_than_price_backfilled = series_time_greater_than_price.reindex(index_equal_to_price.union(series_time_greater_than_price.index)).fillna(method='backfill')
series_to_concat.append(time_greater_than_price_backfilled.reindex(index_equal_to_price))
df['next_time'] = pd.concat(series_to_concat, sort=False)
print(df)
time price next_time
0 15 10.00 30.0
1 30 10.01 75.0
2 45 10.00 60.0
3 60 10.01 75.0
4 75 10.02 NaN
5 90 9.99 NaN
这让我得到了想要的结果。当扩展到一些大型数据帧时,计算可能需要几分钟。有谁对如何解决这个问题有更好的想法?
编辑:约束的澄清
我们可以假设数据帧按时间排序。另一种表达方式是,给定任何行n (Time_ n , Price_ n ), 0 <= n <= len(df) - 1,找到x使得 Time_ x > Time_ n AND Price_ x > Price_ n AND 存在不存在y使得n < y < x且 Price_ y > Price_ n。
慕斯王
哆啦的时光机
喵喔喔
相关分类