【发布时间】:2014-02-19 14:07:21
【问题描述】:
在 Pandas 中,我正在尝试手动编写卡方检验。我在下面的数据框中将row 0 与row 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