python - Pandas:行和列总和的外积

标签 python r pandas outer-join chi-squared

在 Pandas 中,我正在尝试手动编写卡方检验代码。我正在比较下面数据框中的 row 0row 1

data
       2      3      5      10     30
0      3      0      6      5      0
1  33324  15833  58305  54402  38920

为此,我需要计算每个单元格的预期单元格计数:cell(i,j) = rowSum(i)*colSum(j)/sumAll。在 R 中,我可以简单地通过使用 outer() 产品来做到这一点:

Exp_counts <- outer(rowSums(data), colSums(data), "*")/sum(data)    # Expected cell counts

我用numpy的外积函数模仿了上面R代码的结果:

import numpy as np
pd.DataFrame(np.outer(data.sum(axis=1),data.sum(axis=0))/ (data.sum().sum()), index=data.index, columns=data.columns.values)
       2      3      5      10     30
0      2      1      4      3      2
1  33324  15831  58306  54403  38917

是否可以使用 Pandas 函数实现此目的?

最佳答案

仅使用 Pandas 内置方法的完整解决方案:

def outer_product(row):
    numerator = df.sum(1).mul(row.sum(0))
    denominator = df.sum(0).sum(0)
    return (numerator.floordiv(denominator))

df.apply(outer_product)

Image

时间:对于 100 万行 DF。

enter image description here

关于python - Pandas:行和列总和的外积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21402830/

相关文章:

python - 从回调函数渲染数据表 - Dash

python - pandas MultiIndex 滚动平均值

python - 使用 Pandas 在excel文件中搜索column_names的起始列和行

r - 在 R Markdown 中将数据框显示为表格

python - 下降栏是周末。选择仅工作日索引的列

python - 当有多个变量时使用lambda在python数据帧中实现if-else

python - 在数据框中创建字典类型列

r - 在嵌套列表中的矩阵上使用 rbind?

r - 如何编写循环/函数来计算不同行/因素之间的百分比差异?

python - 如何在 numpy 中使基于序列的函数更快?