4

I want to fill missing values in my pandas series, if there are less than 3 consecutive NANs.

Original series with missing values:

s=pd.Series(pd.np.random.randn(20))
s[[1,3,5,7,12,13,14,15, 18]]=pd.np.nan

Gives:

0     0.444025
1          NaN
2     0.631753
3          NaN
4    -0.577121
5          NaN
6     1.299953
7          NaN
8    -0.252173
9     0.287641
10    0.941953
11   -1.624728
12         NaN
13         NaN
14         NaN
15         NaN
16    0.998952
17    0.195698
18         NaN
19   -0.788995

BUT, using pandas.fillna() with a limit only fills the # of values specified (not number of CONSECUTIVE NANs, as expected):

s.fillna(value=0, limit=3) #Fails to fill values at position 7 and forward

Desired output would fill NANs with 0 at positions 1,3,5,7, and 18. It would leave series of 4 NaNs in place in position 12-15.

The documentation and other posts on SO have not resolved this issue (e.g. here). Documentation seems to imply that this limit will work on consecutive NANs, not the overall # in entire dataset that will be filled. Thanks!

4

4 回答 4

5

我们首先通过查找nan值在哪里pd.Series.notna

当我们使用cumsum时,每当遇到非空值时,我们都会增加累积和,这会为连续nan值生成方便的组。

但是,对于除第一组(可能还有第一组)之外的所有对象,我们都以非空值开始。因此,我对mask每组中空值的总数求和并求和。

现在我fillna和使用pd.DataFrame.where来掩盖nan价值总和太多的地方。

mask = s.notna()
c_na = (~mask).groupby(mask.cumsum()).transform('sum')
filled = s.fillna(0).where(c_na.le(3))
s.fillna(filled)

0     1.418895
1     0.000000
2    -0.553732
3     0.000000
4    -0.101532
5     0.000000
6    -1.334803
7     0.000000
8     1.159115
9     0.309093
10   -0.047970
11    0.051567
12         NaN
13         NaN
14         NaN
15         NaN
16    0.623673
17   -0.786857
18    0.000000
19    0.310688
dtype: float64

np.bincount这是一种使用和的奇特 Numpy/Pandas 方式pd.factorize

v = s.values
m = np.isnan(v)
f, u = pd.factorize((~m).cumsum())
filled = np.where(
    ~m, v,
    np.where(np.bincount(f, weights=mask)[f] <= 3, 0, np.nan)
)

pd.Series(filled, s.index)

0     1.418895
1     0.000000
2    -0.553732
3     0.000000
4    -0.101532
5     0.000000
6    -1.334803
7     0.000000
8     1.159115
9     0.309093
10   -0.047970
11    0.051567
12         NaN
13         NaN
14         NaN
15         NaN
16    0.623673
17   -0.786857
18    0.000000
19    0.310688
dtype: float64
于 2018-03-20T22:42:44.200 回答
2

也许试试这个?

t=s[s.isnull()];
v=pd.Series(t.index,index=t.index).diff().ne(1).cumsum();
z=v[v.isin(v.value_counts()[v.value_counts().gt(3)].index.values)];
s.fillna(0).mask(s.index.isin(z.index))
Out[348]: 
0    -0.781728
1     0.000000
2    -1.114552
3     0.000000
4     1.242452
5     0.000000
6     0.599486
7     0.000000
8     0.757384
9    -1.559661
10    0.527451
11   -0.426890
12         NaN
13         NaN
14         NaN
15         NaN
16   -1.264962
17    0.703790
18    0.000000
19    0.953616
dtype: float64
于 2018-03-21T01:12:54.420 回答
2

首先,构建一个 na cum_count 列。连续的 nas 将具有相同的 cum_count。

df = s.to_frame('value').assign(na_ct=s.notna().cumsum())

然后我们可以按 na cum_count 进行分组,检查每个组中的行数并决定天气是否填充 nas。

df.groupby(df.na_ct).apply(lambda x: x if len(x)>4 else x.fillna(0)).value
Out[76]: 
0     0.195634
1     0.000000
2    -0.818349
3     0.000000
4    -2.347686
5     0.000000
6    -0.464040
7     0.000000
8     0.179321
9     0.356661
10    0.471832
11   -1.217082
12         NaN
13         NaN
14         NaN
15         NaN
16   -0.112744
17   -2.630191
18    0.000000
19   -0.313592
Name: value, dtype: float64
于 2018-03-21T01:05:56.303 回答
1

您可以rolling通过以下方式使用 operator 进行尝试:

1) 创建一个仅当窗口中的值小于 X 时才返回 0 的函数

fillnaiflessthan(series, count):
    if series.isnull().sum() < count and series.center == pd.NaN:
         return 0

2)然后在里面使用rolling

s.rolling(window=5, center=True, min_periods=0).apply(lambda x: fillnaiflessthan(x, 4))
于 2018-03-20T23:12:54.933 回答