【发布时间】:2017-05-20 16:41:31
【问题描述】:
我创建了一个函数,该函数将 Pandas 数据框中的 NaN 替换为相应列的平均值。我用一个小数据框测试了这个函数,它工作正常。当我将它应用于更大的数据框(30,000 行,9 列)时,我收到了错误消息:IndexError: index out of bounds
函数如下:
# The 'update' function will replace all the NaNs in a dataframe with the mean of the respective columns
def update(df): # the function takes one argument, the dataframe that will be updated
ncol = df.shape[1] # number of columns in the dataframe
for i in range(0 , ncol): # loops over all the columns
df.iloc[:,i][df.isnull().iloc[:, i]]=df.mean()[i] # subsets the df using the isnull() method, extracting the positions
# in each column where the
return(df)
我用来测试函数的小数据框如下:
0 1 2 3
0 NaN NaN 3 4
1 NaN NaN 7 8
2 9.0 10.0 11 12
你能解释一下错误吗?我们将不胜感激您的建议。
【问题讨论】:
标签: python function pandas indexoutofboundsexception nan