增加大熊猫数据帧插补性能

时间:2016-06-07 12:34:47

标签: python pandas optimization runtime

我想使用pandas来估算大型数据矩阵(90 * 90000)以及更大的数据矩阵(150000 * 800000)。 目前我正在测试我的笔记本电脑上的较小的一个(8GB RAM,Haswell核心i5 2.2 GHz,更大的数据集将在服务器上运行)。

列中有一些缺失值,我想用最频繁的一行来估算。

我的工作代码是:

freq_val =  pd.Series(mode(df.ix[:,6:])[0][0], df.ix[:,6:].columns.values) #most frequent value per column, starting from the first SNP column (second row of 'mode'gives actual frequencies)
df_imputed = df.ix[:,6:].fillna(freq_val) #impute unknown SNP values with most frequent value of respective columns

我的机器上的插补大约需要20分钟。是否有另一种可以提高性能的实现?

2 个答案:

答案 0 :(得分:2)

试试这个:

df_imputed = df.iloc[:, 6:].fillna(df.iloc[:, 6:].apply(lambda x: x.mode()).iloc[0])

答案 1 :(得分:2)

我尝试了不同的方法。关键的学习是mode函数真的很慢。或者,我使用np.uniquereturn_counts=True)和np.bincount实现了相同的功能。后者应该更快,但它不适用于NaN值。

优化的代码现在需要大约28秒才能运行。 MaxU的答案需要在我的机器上完成约48秒才能完成。

代码:

iter = range(np.shape(df.ix[:,6:])[1])
freq_val = np.zeros(np.shape(df.ix[:,6:])[1])
for i in iter:
    _, count = np.unique(df.ix[:,i+6], return_counts=True)
    freq_val[i] = count.argmax()
freq_val_series =  pd.Series(freq_val, df.ix[:,6:].columns.values) 
df_imputed = df.ix[:,6:].fillna(freq_val_series) 

感谢您的投入!

相关问题