scipy 中的 Fisher 精确作为使用 pandas 的新列

Fisher's Exact in scipy as new column using pandas

使用ipython笔记本,一个pandas数据框有4列:numerator1, numerator2, 分母 1分母 2.

在不遍历每条记录的情况下,我试图创建名为 FishersExact 的第五列。我希望列的值存储由 scipy.stats.fisher_exact 返回的元组,使用四列中每一列的值(或值的某些派生)作为我的输入。

df['FishersExact'] = scipy.stats.fisher_exact( [[df.numerator1, df.numerator2],
[df.denominator1 - df.numerator1 , df.denominator2 - df.numerator2]])

Returns:

/home/kevin/anaconda/lib/python2.7/site-packages/scipy/stats/stats.pyc in fisher_exact(table, alternative)
2544     c = np.asarray(table, dtype=np.int64)  # int32 is not enough for the algorithm
2545     if not c.shape == (2, 2):
-> 2546         raise ValueError("The input `table` must be of shape (2, 2).")
2547 
2548     if np.any(c < 0):

ValueError: The input `table` must be of shape (2, 2).

当我只索引数据框的第一条记录时:

odds,pval = scipy.stats.fisher_exact([[df.numerator1[0], df.numerator2[0]], 
[df.denominator1[0] - df.numerator1[0], df.denominator2[0] -df.numerator2[0]]])

这是返回:

1.1825710754 0.581151431104

我本质上是在尝试模拟类似于以下的算术功能:

df['freqnum1denom1'] = df.numerator1 / df.denominator1

其中 returns 添加到数据框的新列,其中每个记录的频率都在新列中。

可能遗漏了什么,不胜感激,谢谢!

看起来您正在构建一个 pandas 系列的矩阵,并将其传递给函数。该函数需要一个标量矩阵;你可以多次调用它。这两件事不太一样。

这里有(至少)两种方式。

使用apply

您可以为此使用 pandasapply

df['FishersExact'] = df.apply(
    lambda r: scipy.stats.fisher_exact([[r.numerator1, ... ]]),
    axis=1)

注意以下几点:

  • axis=1 对每一行应用一个函数。

  • lambda中,r.numerator是一个标量。

回归基础

Fischer's exact test可以说是原列中的向量化运算,应该会快很多。要最大程度地提高速度,您需要使用阶乘的矢量化版本(我不知道)。这甚至可以是一个单独的(很好!)SO 问题。