在python

时间:2017-05-10 06:19:09

标签: python genomicranges

我有一个带有基因组箱的数据框,格式如下。每个基因组范围表示为行,并且单元格值对应于bin的开始。

        0       1       2       3      4      5    ...   522  

0    9248    9249     NaN     NaN     NaN    NaN   ...   NaN
1   17291   17292   17293   17294   17295    NaN   ...   NaN
2   18404   18405   18406   18407     NaN    NaN   ...   NaN

[69 rows x 522 columns]

如您所见,许多行值不完整,因为某些基因组范围比其他基因组范围小。

我希望为整个行中的每个索引进行成对组合。如果每个成对交互作为单独的数据框存储(最好是偶数),那就没问题了。

我想要这样的事情:

0 - 1 Pairwise:
0      1
9248   17291
9248   17292
9248   17293
9248   17294
9248   17295
9249   17291
9249   17292
9249   17293
9249   17294
9249   17295
[10 rows x 2 columns]

0 - 2 Pairwise:
0       2
9248   18404
9248   18405
9248   18406
9248   18407
9249   18404
9249   18405
9249   18406
9249   18407
[8 rows x 2 columns]

我需要每个成对行组合的每个值组合。我想我需要使用itertools.product()来做这类事情,但无法弄清楚如何编写适当的循环。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

<强>设置

from pandas.tools.util import cartesian_product as cp

df = pd.DataFrame({'0': {0: 9248, 1: 17291, 2: 18404},
 '1': {0: 9249, 1: 17292, 2: 18405},
 '2': {0: np.nan, 1: 17293.0, 2: 18406.0},
 '3': {0: np.nan, 1: 17294.0, 2: 18407.0},
 '4': {0: np.nan, 1: 17295.0, 2: np.nan},
 '5': {0: np.nan, 1: np.nan, 2: np.nan},
 '522': {0: np.nan, 1: np.nan, 2: np.nan}})

<强>解决方案

final={}
# use cartesian_product to get all the combinations for each row with other rows and add the results to the final dictionary.
df.apply(lambda x: [final.update({(x.name, i): np.r_[cp([x.dropna(), df.iloc[i].dropna()])].T}) for i in range(x.name+1,len(df))], axis=1)

<强>验证

for k, v in final.items():
    print(k)
    print(v)

(0, 1)
[[  9248.  17291.]
 [  9248.  17292.]
 [  9248.  17293.]
 ..., 
 [  9249.  17293.]
 [  9249.  17294.]
 [  9249.  17295.]]
(1, 2)
[[ 17291.  18404.]
 [ 17291.  18405.]
 [ 17291.  18406.]
 ..., 
 [ 17295.  18405.]
 [ 17295.  18406.]
 [ 17295.  18407.]]
(0, 2)
[[  9248.  18404.]
 [  9248.  18405.]
 [  9248.  18406.]
 ..., 
 [  9249.  18405.]
 [  9249.  18406.]
 [  9249.  18407.]]