如何用滚动平均值在 pandas 中填充nan值 [英] How to fill nan values with rolling mean in pandas
问题描述
我有一个数据框,它在几个地方包含nan值。我正在尝试执行数据清理,在其中使用前五个实例的平均值填充nan值。为此,我提出了以下建议。
I have a dataframe which contains nan values at few places. I am trying to perform data cleaning in which I fill the nan values with mean of it's previous five instances. To do so, I have come up with the following.
input_data_frame[var_list].fillna(input_data_frame[var_list].rolling(5).mean(), inplace=True)
但是,这不起作用。它没有满足nan值。在上述操作之前和之后,数据框的空计数没有变化。假设我的数据框只有整数列,如何用前五个实例的平均值填充NaN值?
But, this is not working. It isn't filling the nan values. There is no change in the dataframe's null count before and after the above operation. Assuming I have a dataframe with just integer column, How can I fill NaN values with mean of the previous five instances? Thanks in advance.
推荐答案
这应该有效:
input_data_frame[var_list]= input_data_frame[var_list].fillna(pd.rolling_mean(input_data_frame[var_list], 6, min_periods=1))
请注意,窗口
为 6
,因为它包含 NaN
本身的值(不计入平均值)。同样,其他 NaN
值也不用于平均值,因此,如果在窗口中找到的值少于5个,则将根据实际值计算平均值。
Note that the window
is 6
because it includes the value of NaN
itself (which is not counted in the average). Also the other NaN
values are not used for the averages, so if less that 5 values are found in the window, the average is calculated on the actual values.
例如:
df = {'a': [1, 1,2,3,4,5, np.nan, 1, 1, 2, 3, 4, 5, np.nan] }
df = pd.DataFrame(data=df)
print df
a
0 1.0
1 1.0
2 2.0
3 3.0
4 4.0
5 5.0
6 NaN
7 1.0
8 1.0
9 2.0
10 3.0
11 4.0
12 5.0
13 NaN
输出:
a
0 1.0
1 1.0
2 2.0
3 3.0
4 4.0
5 5.0
6 3.0
7 1.0
8 1.0
9 2.0
10 3.0
11 4.0
12 5.0
13 3.0
这篇关于如何用滚动平均值在 pandas 中填充nan值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!