我想知道如何將資料集中的 NaN 替換為 5 個最后一個值的最后平均值。
| A欄 | B欄 |
|---|---|
| 1 | 2 |
| 2 | 5 |
| 3 | 5 |
| 4 | 2 |
| 5 | 2 |
| 鈉 | 2 |
| 鈉 | 2 |
| 1 | 2 |
| 1 | 2 |
| 1 | 2 |
| 1 | 鈉 |
| 1 | 2 |
| 1 | 2 |
例如,在這種情況下,第一個 NaN 將是 (1,2,3,4,5) 的平均值,第二個 NaN 將是 (2,3,4,5,另一個 NaN 的值) 的平均值。
我努力了
df.fillna(df.mean())
uj5u.com熱心網友回復:
如前所述,已在此處回答,但最新 pandas 版本的更新版本如下:
data={'col1':[1,2,3,4,5,np.nan,np.nan,1,1,1,1,1,1],
'col2':[2,5,5,2,2,2,2,2,2,2,np.nan,2,2]}
df=pd.DataFrame(data)
window_size = 5
df=df.fillna(df.rolling(window_size 1, min_periods=1).mean())
輸出:
col1 col2
0 1.0 2.0
1 2.0 5.0
2 3.0 5.0
3 4.0 2.0
4 5.0 2.0
5 3.0 2.0
6 3.5 2.0
7 1.0 2.0
8 1.0 2.0
9 1.0 2.0
10 1.0 2.0
11 1.0 2.0
12 1.0 2.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527141.html
上一篇:關于python中的ifelse和mathematic的問題
下一篇:如何計算熊貓中不常見的缺失值
