python - 如何找到 DataFrame 行的所有组合?

如果这个问题与论坛中其他人提出的问题相似,我很抱歉,但我找不到足够相似的问题。我有一个包含 9 列和 3 行的 df,我想找到这些行之间所有可能的组合。我尝试使用 itertools 包中的组合,但我似乎无法使其工作。 我想要的输出将是所有可能组合的列表。谢谢你,如果它与其他问题相似,我们深表歉意。

import pandas as pd
from itertools import combinations

df1 = pd.DataFrame({"Main1": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main2": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main3": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main4": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main5": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main6": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main7": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main8": ["Outcome1", "Outcome2", "Outcome3"],
                    "Main9": ["Outcome1", "Outcome2", "Outcome3"]})

    Main1   Main2   Main3   Main4   Main5   Main6   Main7   Main8   Main9
0   Outcome1    Outcome1    Outcome1    Outcome1    Outcome1    Outcome1    Outcome1    Outcome1    Outcome1
1   Outcome2    Outcome2    Outcome2    Outcome2    Outcome2    Outcome2    Outcome2    Outcome2    Outcome2
2   Outcome3    Outcome3    Outcome3    Outcome3    Outcome3    Outcome3    Outcome3    Outcome3    Outcome3

all_combinations = list(combinations(df1, 3))

编辑:较小的样本和所需的输出:

df1 = pd.DataFrame({"Main1": ["Outcome1", "Outcome2", "Outcome3"], "Main2": ["Outcome1", "Outcome2", "Outcome3"]}) 

期望的输出是这样的:

[["Outcome1","Outcome1"], ["Outcome1","Outcome2"], ["Outcome1","Outcome3"], ["Outcome2","Outcome1"], ["Outcome2","Outcome2"], ["Outcome2","Outcome3"], ["Outcome3","Outcome1"], ["Outcome3","Outcome2"], ["Outcome3","Outcome3"]] 

最佳答案

您正在寻找列表自身的笛卡尔积。

from itertools import product

options = ['Outcome1', 'Outcome2', 'Outcome3']

result = product(options, options)
print(*result, sep='\n')

输出

('Outcome1', 'Outcome1')
('Outcome1', 'Outcome2')
('Outcome1', 'Outcome3')
('Outcome2', 'Outcome1')
('Outcome2', 'Outcome2')
('Outcome2', 'Outcome3')
('Outcome3', 'Outcome1')
('Outcome3', 'Outcome2')
('Outcome3', 'Outcome3')

https://stackoverflow.com/questions/63755011/

相关文章:

r - “Enter”键不会与 splashR::splash_send_key 一起发送

reactjs - Jest 测试因 gatsby webpack 配置而抛出错误

reactjs - reactstrap Collapse 没有出现在手机上

c - 尝试将 'insert' 或 'add' 写入文本文件 - 一个小问题

css - 如何将边框颜色作为线性渐变放在表格行边框上?

apache-spark - 有什么方法可以使用 spark 从 s3 并行读取多个 Parquet

ios - 使用共享的 iOS Keychain 启用跨应用程序 Firebase 身份验证

api - Google Scripts 应用程序和 Plaid 链接身份验证

python - Pygame 全屏放大

python - 未处理的异常 : Connection closed while receivin