我有一个带有以下格式的基因组区域的数据框。每个基因组范围都表示为一行,并且像元值对应于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()来执行此类操作,但无法弄清楚如何编写适当的循环。任何帮助是极大的赞赏!

最佳答案

设定

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.]]

关于python - 在python中的成对行比较中迭代所有值组合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43884877/

10-09 02:47