使用ipython notebook,pandas数据框有4列: numerator1 , numerator2 , denominator1 和 denominator2 。
在没有遍历每条记录的情况下,我正在尝试创建一个名为FishersExact的第五列。我希望列的值存储由scipy.stats.fisher_exact返回的元组,使用四列中每一列的值(或值的某些推导)作为我的输入。
df['FishersExact'] = scipy.stats.fisher_exact( [[df.numerator1, df.numerator2],
[df.denominator1 - df.numerator1 , df.denominator2 - df.numerator2]])
返回:
/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
返回添加到数据框的新列,其中每个记录的频率都在新列中。
可能遗漏了一些东西,任何方向都会非常感谢,谢谢!
答案 0 :(得分:1)
看起来您正在构建pandas
系列的矩阵,并将其传递给函数。该函数需要一个标量矩阵;你可以多次打电话。这两件事情并不完全相同。
至少有两种方法可以去这里。
使用apply
您可以使用pandas
的{{3}}。
df['FishersExact'] = df.apply(
lambda r: scipy.stats.fisher_exact([[r.numerator1, ... ]]),
axis=1)
请注意以下事项:
axis=1
将函数应用于每一行。
在lambda
内,r.numerator
是标量。
返回基础知识
apply
可以描述为原始列中的矢量化操作,这应该快得多。要将速度提高到最大值,您需要使用阶乘的矢量化版本(我不知道)。这甚至可能是一个单独的(好的!)SO问题。