[英]Pandas Fill consecutive null values with range of values between the first non null value before and after
我有一個 dataframe,我想在以下兩個條件下在 dataframe 中填充 null 值
條件 1: NaN 之后的值(in this example 10)
> NaN 之前的值(7.5)
2.75
7.5
NaN
NaN
NaN
10
從 7.5 到 10 同樣遞增。所以就像
2.75
7.5
8.125
8.75
9.375
10
PS:增量計算如下(10-7.5/4) = 0.625
條件2: NaN之后的值<=Nan之前的值
2.75
10
NaN
NaN
NaN
7.5
前向填充 NaN 值
2.75
10
10
10
10
7.5
如果您的目標是為系列做這件事,您可以使用:
df['Col'].fillna(df['Col'].interpolate().cummax())
對於 dataframe:
df.fillna(df.interpolate().cummax())
為 con1 和 cond 2 顯示 dataframe(也可以為系列復制)
print(df1)
Col Col1
0 2.75 2.75
1 7.50 10.00
2 NaN NaN
3 NaN NaN
4 NaN NaN
5 10.00 7.50
print(df1.fillna(df1.interpolate().cummax()))
Col Col1
0 2.750 2.75
1 7.500 10.00
2 8.125 10.00
3 8.750 10.00
4 9.375 10.00
5 10.000 7.50
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.