使用 fillna 遍历列

Iterate over a column using fillna

我有以下 dfDay 列中重复出现:

     Day    Value
0     0      1.0
1   NaN      1.6
2   NaN      1.0
3   NaN      1.7
4   NaN      6.0
5     0      9.0
6   NaN      7.8
7   NaN      2.5
8   NaN      1.2
9   NaN      3.4
...

我想 fillna 在每一行中递增 +1。因此得到这个输出:

    Day     Value
0     0       1.0
1     1       1.6
2     2       1.0
3     3       1.7
4     4       6.0
5     0       9.0
6     1       7.8
7     2       2.5
8     3       1.2
9     4       3.4
...

我试过了df.Day.fillna(value = dfs.iloc[-1]['Day] + 1, inplace = True)

但它不起作用。

你可以使用这个功能(编辑:import numpy as np之前):

>>> def func(iterable):
...     counter = 1
...     out = []
...     for item in iterable:
...         if item == 0:
...             out.append(0)
...             counter = 1
...         elif np.isnan(item) == True:
...             out.append(counter)
...             counter += 1
...     return out

给定数据框 x:

>>> x
   Day
0  0.0
1  NaN
2  NaN
3  NaN
4  NaN
5  0.0
6  NaN
7  NaN
8  NaN
9  NaN
>>> x['Day'] = func(x['Day'])
>>> x
   Day
0    0
1    1
2    2
3    3
4    4
5    0
6    1
7    2
8    3
9    4

cumsum计算累计总和。

df.fillna(1, inplace=True)
df['Day'] = df['Day'].groupby((df['Day']- df['Day'].shift()!=0).cumsum()).cumsum()

df
    Day Value
0   0.0 1.0
1   1.0 1.6
2   2.0 1.0
3   3.0 1.7
4   4.0 6.0
5   0.0 9.0
6   1.0 7.8
7   2.0 2.5
8   3.0 1.2
9   4.0 3.4