[英]Python pandas fill missing value (NaN) based on condition of another column
[英]Pandas - fill NaN based on the previous value of another cell
我正在重新采樣的數據框中有一些股票數據,這導致一些NaN值。 這是原始供稿的一部分:
In [34]: feeddf
Out[34]:
open high low close volume
date
2017-12-03 07:00:00 14.46 14.46 14.46 14.46 25000
2017-12-03 07:01:00 14.46 14.46 14.46 14.46 20917
2017-12-03 07:06:00 14.50 14.50 14.50 14.50 2000
2017-12-03 07:12:00 14.50 14.56 14.50 14.56 17000
該提要應該是每分鍾一分鍾,但是當沒有可用數據時,將跳過該行。 重新采樣數據框並匯總開盤價,高點,低點和閉合時,看起來像這樣:
In [35]: feeddf.resample('3Min').agg({'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last'})
Out[35]:
open high low close
date
2017-12-03 07:00:00 14.46 14.46 14.46 14.46
2017-12-03 07:03:00 NaN NaN NaN NaN
2017-12-03 07:06:00 14.50 14.50 14.50 14.50
2017-12-03 07:09:00 NaN NaN NaN NaN
2017-12-03 07:12:00 14.50 14.56 14.50 14.56
我的問題 :我想根據最后一行的close
價向前填充丟失的數據。 df.fillna(method='ffill')
沒有幫助,因為它基於同一列上的最后一個值填充它。 任何想法?
第一前進補最后一列close
,然后bfill
按列:
print (df)
open high low close
date
2017-12-03 07:00:00 14.46 14.46 14.46 14.81
2017-12-03 07:03:00 NaN NaN NaN NaN
2017-12-03 07:06:00 14.50 14.50 14.50 14.59
2017-12-03 07:09:00 NaN NaN NaN NaN
2017-12-03 07:12:00 14.50 14.56 14.50 14.56
df['close'] = df['close'].ffill()
df = df.bfill(axis=1)
print (df)
open high low close
date
2017-12-03 07:00:00 14.46 14.46 14.46 14.81
2017-12-03 07:03:00 14.81 14.81 14.81 14.81
2017-12-03 07:06:00 14.50 14.50 14.50 14.59
2017-12-03 07:09:00 14.59 14.59 14.59 14.59
2017-12-03 07:12:00 14.50 14.56 14.50 14.56
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.