2024-04-24 05:11:16 发布
网友
我想用缺失值前后单元格的平均值来填充pandas数据帧中缺失的值。所以如果它是[1,NaN,3],那么NaN值应该是2,因为(1+3)/2。我找不到任何方法来做熊猫或Scikit learn。有办法吗?在
如果您没有任何NaN值作为最后一个索引,这将起作用,而您的插补方法暗示这是正确的。在
NaN
>>> data = pd.DataFrame({'a': [10, 6, -3, -2, 4, 12, 3, 3], 'b': [6, -3, np.nan, 12, 8, 11, -5, -5], 'id': [1, 1, 1, 1, np.nan, 2, 2, 4]}) >>> data a b id 0 10 6.0 1.0 1 6 -3.0 1.0 2 -3 NaN 1.0 3 -2 12.0 1.0 4 4 8.0 NaN 5 12 11.0 2.0 6 3 -5.0 2.0 7 3 -5.0 4.0 >>> nan_cols = data.columns[data.isnull().any(axis=0)] >>> for col in nan_cols: ... for i in range(len(data)): ... if pd.isnull(data.loc[i, col]): ... data.loc[i, col] = (data.loc[i-1, col] + data.loc[i+1, col])/2 >>> data a b id 0 10 6.0 1.0 1 6 -3.0 1.0 2 -3 4.5 1.0 3 -2 12.0 1.0 4 4 8.0 1.5 5 12 11.0 2.0 6 3 -5.0 2.0 7 3 -5.0 4.0
使用spies006的df示例。在
df = pd.DataFrame({'a': [10, 6, -3, -2, 4, 12, 3, 3], 'b': [6, -3, np.nan, 12, 8, 11, -5, -5], 'id': [1, 1, 1, 1, np.nan, 2, 2, 4]}) #use np.where to locate the nans and fill it with the average of surrounding elements. df.where(df.notnull(), other=(df.fillna(method='ffill')+df.fillna(method='bfill'))/2) Out[2517]: a b id 0 10 6.0 1.0 1 6 -3.0 1.0 2 -3 4.5 1.0 3 -2 12.0 1.0 4 4 8.0 1.5 5 12 11.0 2.0 6 3 -5.0 2.0 7 3 -5.0 4.0
考虑这个数据帧
df = pd.DataFrame({'val': [1,np.nan, 4, 5, np.nan, 10]}) val 0 1.0 1 NaN 2 4.0 3 5.0 4 NaN 5 10.0
您可以使用fillna和shift()来获得所需的输出
你得到了
val 0 1.0 1 2.5 2 4.0 3 5.0 4 7.5 5 10.0
如果您没有任何
NaN
值作为最后一个索引,这将起作用,而您的插补方法暗示这是正确的。在使用spies006的df示例。在
考虑这个数据帧
您可以使用fillna和shift()来获得所需的输出
^{pr2}$你得到了
相关问题 更多 >
编程相关推荐