You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas基于日期列前一日数据填充Price列的NaN值

Fill NaN with Previous Day's Price Using pandas.fillna()

Hey there! Let's work through how to fill that NaN value with the previous day's price properly—we need to make sure we're handling dates in the right order first, which is key here.

Step 1: Reproduce the original DataFrame

First, let's set up your initial data (we'll need pandas and numpy imported):

import pandas as pd
import numpy as np

df = pd.DataFrame({
    "date": ["2018-12-21", "2018-12-22", "2018-05-04"], 
    "price": [100, np.nan, 105]
})

Your original output looks like this:

date  price
0  2018-12-21  100.0
1  2018-12-22    NaN
2  2018-05-04  105.0

Step 2: Fix date formatting and sort chronologically

Notice your dates are out of order (2018-05-04 comes after two December dates). To make sure we pull the actual previous calendar day's price, we first convert the date column to datetime type, then sort the DataFrame by date:

# Convert date column to datetime for proper date handling
df['date'] = pd.to_datetime(df['date'])

# Sort DataFrame so dates are in chronological order
df = df.sort_values('date').reset_index(drop=True)

Now our sorted DataFrame is:

date  price
0 2018-05-04  105.0
1 2018-12-21  100.0
2 2018-12-22    NaN

Step 3: Fill NaN with the previous day's price

Now we can use fillna() with method='ffill' (forward fill) to replace the NaN with the immediately preceding row's price. Since we sorted the dates, this is exactly the previous calendar day's value:

df['price'] = df['price'].fillna(method='ffill')

Final Result

After running the code above, your DataFrame will have the NaN filled correctly:

date  price
0 2018-05-04  105.0
1 2018-12-21  100.0
2 2018-12-22  100.0

Quick Note

  • If you skip sorting, ffill would just pull the value from the row above in the original unsorted DataFrame—which might not be the actual previous calendar day. Always sort dates first when working with time-series fills!

内容的提问来源于stack exchange,提问作者Gen Tan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:06:55