gpt4 book ai didi

python - 在python中迭代成对行比较中的所有值组合

转载 作者:太空宇宙 更新时间:2023-11-03 15:16:02 24 4
gpt4 key购买 nike

我有一个包含以下格式的基因组箱的数据框。每个基因组范围都表示为一行,单元格值对应于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com