我有以下两个数据框:
import pandas as pd
import scipy.stats
import numpy as np
df_a = pd.DataFrame({
's1': [10,10,12,13,14,15],
's2': [100,100,112,1.3,14,125],
's2': [13,200,10,13,14.5,10.5],
'gene_symbol': ['a', 'b', 'c', 'd', 'e', 'f'],
})
df_b = pd.DataFrame({
's1': [15,20,123,13,14,15,1],
's2': [130,100,72,1.3,14,125,2],
's2': [213,200,35.4,13,414.5,130.5,3],
'gene_symbol': ['a', 'b', 'c', 'd', 'e', 'f','g'],
})
df_a.set_index('gene_symbol', inplace=True)
df_b.set_index('gene_symbol', inplace=True)
看起来像这样:
s1 s2
gene_symbol
a 10 13.0
b 10 200.0
c 12 10.0
d 13 13.0
e 14 14.5
f 15 10.5
In [51]: df_b
Out[51]:
s1 s2
gene_symbol
a 15 213.0
b 20 200.0
c 123 35.4
d 13 13.0
e 14 414.5
f 15 130.5
g 1 3.0
我想做的是逐个基因地计算 T 检验 p 值。 例如对于基因 a 我们将有
In [47]: scipy.stats.ttest_ind([ 10,13.0],[15,213.0])
Out[47]: Ttest_indResult(statistic=-1.0352347135782713, pvalue=0.4093249100598676)
我如何将其应用于共享两个数据帧的公共(public)基因的所有行(例如,忽略 df_b 中的基因 g)。
我试过了,但失败了:
scipy.stats.ttest_ind(df_a, df_b,axis=1)
请您参考如下方法:
您可以通过匹配两个数据帧或索引,使用您的 gene_symbol 索引删除 g 行。
您可以使用 pandas.merge()在匹配的列或索引上连接两个 DataFrame,并在 ttest_ind 上使用合并后的 DataFrame 的列:
# default join is inner
df_m = pd.merge(df_a, df_b, left_index=True, right_index=True)
scipy.stats.ttest_ind(df_m.ix[:, :2], df_m.ix[:, 2:], axis=1)
或者您可以找到 intersection索引并使用它们来切片您的数据集:
idx = df_a.index.intersection(df_b.index)
scipy.stats.ttest_ind(df_a.loc[idx], df_b.loc[idx], axis=1)
