【发布时间】:2013-01-28 15:28:38
【问题描述】:
我正在编写一个函数来计算 pd.DataFrame 中所有列的条件概率,该 pd.DataFrame 具有 ~800 列。我写了几个版本的函数,发现两个主要选项的计算时间有很大差异:
col_sums = data.sum() #Simple Column Sum over 800 x 800 DataFrame
选项 #1: {'col_sums' 和 'data' 分别是 Series 和 DataFrame}
[这包含在 index1 和 index2 上的循环中以获取所有组合]
joint_occurance = data[index1] * data[index2]
sum_joint_occurance = joint_occurance.sum()
max_single_occurance = max(col_sum[index1], col_sum[index2])
cond_prob = sum_joint_occurance / max_single_occurance #Symmetric Conditional Prob
results[index1][index2] = cond_prob
对比。
选项#2: [同时遍历 index1 和 index2 以获取所有组合] 唯一的区别是我在循环之前将 data_matrix 导出到 np.array 而不是使用 DataFrame
new_data = data.T.as_matrix() [Type: np.array]
选项 #1 运行时间约为 1700 秒 选项 #2 运行时间约为 122 秒
问题:
- 将 DataFrames 的内容转换为 np.array 最适合计算任务吗?
- pandas 中的 .sum() 例程与 NumPy 中的 to .sum() 例程有显着不同,还是由于标签访问数据而导致速度差异?
- 为什么这些运行时如此不同?
【问题讨论】:
-
我建议您将函数移植到 Cython 而不是纯 Python。