[英]Pandas missing values : fill with the closest non NaN value
假設我有一個連續幾個NaN的熊貓系列。 我知道fillna
有幾種填充缺失值的方法( backfill
和fill forward
),但我想用最接近的非NaN值填充它們。 這是我的一個例子:
`s = pd.Series([0, 1, np.nan, np.nan, np.nan, np.nan, 3])`
以及我想要的一個例子: s = pd.Series([0, 1, 1, 1, 3, 3, 3])
有誰知道我能做到嗎?
謝謝!
您可以將Series.interpolate
與method='nearest'
:
In [11]: s = pd.Series([0, 1, np.nan, np.nan, np.nan, np.nan, 3])
In [12]: s.interpolate(method='nearest')
Out[12]:
0 0.0
1 1.0
2 1.0
3 1.0
4 3.0
5 3.0
6 3.0
dtype: float64
In [13]: s = pd.Series([0, 1, np.nan, np.nan, 2, np.nan, np.nan, 3])
In [14]: s.interpolate(method='nearest')
Out[14]:
0 0.0
1 1.0
2 1.0
3 2.0
4 2.0
5 2.0
6 3.0
7 3.0
dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.