使用Pandas基于日期列前一日数据填充Price列的NaN值
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,
ffillwould 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

