![](/img/trans.png)
[英]Python: How to populate Pandas column that depends on the previous value (previous row)?
[英]How to populate missing row with previous or next row in pandas python
我有這樣的示例數據。
date time option_type open high low close volume
6031 9/27/2018 09:17 CE 11500 0.15 0.15 0.15 0.15 1500
6131 9/27/2018 15:19 CE 11500 0.05 0.05 0.05 0.05 1500
6132 9/27/2018 15:22 CE 11500 0.05 0.05 0.05 0.05 75
6133 9/27/2018 15:24 CE 11500 0.05 0.05 0.05 0.05 225
6134 9/27/2018 15:25 CE 11500 0.05 0.05 0.05 0.05 75
6135 9/27/2018 15:26 CE 11500 0.05 0.05 0.05 0.05 600
一些行在那邊丟失了。 例如09:15、09:16,然后15:20、15:21等。
我想在15:20/15:21的情況下用上一行值填充缺失的行,在09:15/09:16的情況下用下一個可用行填充。 09:17的值將用於09:15/09:16。 15:20的值將用於15:21/15:22。
你能幫我這個忙嗎? 在此先感謝您,感謝您的努力和時間。
步驟1:找出連續列的時間差異:
df['deltaT'] = df.time.to_series().diff().dt.seconds.div(60, fill_value=0)
上面將為您提供一個新的列,列出了差異分鍾數。 在連續的行之間
步驟2:根據新的列deltaT
復制行
df.reindex(df.index.repeat(df.deltaT))
步驟3:建立邏輯以增加時間列
df['time'] = pd.to_timedelta(df['time']) + pd.to_timedelta(df['deltaT'], unit='m')
仍在努力為您做最后一部分。
如果您覺得這有幫助並且可以在此基礎上繼續發展。
我認為您正在尋找這樣的東西:
df['time']=df['time'].fillna(method="ffill") #to carry the values forward
df['time']=df['time'].fillna(method="bfill") #to carry the values backwards
DF
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.