![](/img/trans.png)
[英]Replace NaN values in pandas dataframe with a computation from other columns
[英]How to replace NaN in pandas dataframe with calculated value from other columns
我在下面的數據框中添加了最后一行作為最新數據。
df.tail()
Open High Low Close %K %D
Date
2022-06-22 23.71 25.45 23.55 24.29 21.74 18.01
2022-06-23 24.94 25.57 24.17 25.33 31.30 25.15
2022-06-24 26.11 28.04 26.05 27.98 51.99 35.01
2022-06-27 28.35 28.50 27.00 27.32 47.54 43.61
2022-06-28 27.46 28.21 24.76 24.83 NaN NaN
我想用來自其他列的數據的計算值填充 NaN 值。
我可以用下面的代碼做到這一點,
df['14-high'] = df['High'].rolling(14).max()
df['14-low'] = df['Low'].rolling(14).min()
df['%K'] = (df['Close'] - df['Low'].rolling(14).min())*100/(df['14-high'] - df['14-low'])
df['%D'] = df['%K'].rolling(3).mean()
df.drop(columns=['14-high', '14-low'], inplace=True)
有沒有更好的方法可以在不重新計算 %K 和 %D 列的情況下做到這一點? 即只計算 NaN 單元格而不是整個列。
一種方法是使用pandas fillna() 方法。
您仍然需要第一次計算:
df['14-high'] = df['High'].rolling(14).max()
df['14-low'] = df['Low'].rolling(14).min()
但是您只能更新 %K 和 %D 列中的 NaN 值:
df['%K'].fillna((df['Close'] - df['Low'].rolling(14).min())*100/(df['14-high'] - df['14-low']), inplace=True)
df['%D'].fillna(df['%K'].rolling(3).mean(), inplace=True)
希望我能幫上忙!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.