【问题标题】:Pandas: outer product of row and col sums熊猫:行和列总和的外积
【发布时间】:2014-02-19 14:07:21
【问题描述】:

在 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 功能实现这一点?

【问题讨论】:

  • 这不行吗? 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(..)
  • 是的,确实如此(但我意识到在求和时需要反转轴顺序)。我重新措辞了我的问题,包括 numpy 解决方案。我正在寻找一种使用 Pandas 函数的方法。
  • 为什么还需要 pandas 函数?
  • 我觉得 Pandas 可能能够做到这一点。我想学习。
  • 我认为这可以回答您的问题。 stackoverflow.com/questions/18578686/…

标签: python r pandas outer-join chi-squared


【解决方案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)

时序:100 万行 DF。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-17
    • 2017-10-02
    • 2019-05-20
    • 2019-01-09
    • 1970-01-01
    • 2018-11-08
    • 2017-07-03
    • 2019-07-26
    相关资源
    最近更新 更多