Pandas:行和列求和的外积

4
在Pandas中,我正在尝试手动编写卡方检验。我正在比较下面数据框中的行0行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的outer product函数来模仿上述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函数实现这个吗?

1
这样行不行呢?not_yet_df = np.outer(data.sum(axis=0), data.sum(axis=1))/ (data.sum().sum()) 然后 now_a_df = pd.DataFrame(not_yet_df) 此外,如果你愿意的话,你可以使用 pd.np.outer(..) 直接从 pandas 中调用 outer 函数,而无需导入 numpy。 - mkln
是的,它可以(但我意识到在求和时需要反转轴顺序)。我重新措辞了我的问题,包括numpy解决方案。我正在寻找一种使用Pandas函数来完成这个任务的方法。 - Zhubarb
你到底为什么需要Pandas函数呢? - mkln
1
我觉得Pandas可能能够做到这一点。我想学习。 - Zhubarb
1
我认为这个 StackOverflow 回答了你的问题。 https://dev59.com/ZHbZa4cB1Zd3GeqPFWMA - PabTorre
1个回答

1

使用仅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

计时:对于1百万行的数据框。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接