【问题标题】:How to find some possible combinations of pandas DataFrame given some constraints?给定一些约束,如何找到一些可能的 pandas DataFrame 组合?
【发布时间】:2021-08-30 02:50:40
【问题描述】:

根据以下信息,如何找到大小为 (m*n) 的 pandas DataFrame 的所有可能组合:

  • 组合大小 = n
  • 每个组合不得在同一行或同一列中包含多个元素 示例:对于大小为 (3*2) 的 DataFrame,其中包含以下数据:

我们需要找到 2 个元素的所有可能组合,其中 (1,4) 是有效组合,而 (1,2) 或 (1,3) 无效,因为它们包含来自同一行或同一列的元素

【问题讨论】:

    标签: python pandas algorithm dataframe combinations


    【解决方案1】:

    这是一个低效的简单实现:)

    df = pd.DataFrame({'col1':[1, 3, 5, 7], 'col2':[2, 4, 6, 8], 'col3':[9, 10, 11, 12]})
    def get_all_combinations(dataframe, length):
        assert (len(dataframe.columns)>= length) & (len(dataframe)>= length)
        cols = list(itertools.combinations(dataframe.columns, length))
        rows = list(itertools.combinations(range(len(dataframe)), length))
        for col in cols:
            for row in rows:
                temp_df = dataframe.loc[row, col]
                print([temp_df.iloc[idx, idx] for idx in range(length)])
    get_all_combinations(df, 2)
    

    输出:

    [1, 4]
    [1, 6]
    [1, 8]
    [3, 6]
    [3, 8]
    [5, 8]
    [1, 10]
    [1, 11]
    [1, 12]
    [3, 11]
    [3, 12]
    [5, 12]
    [2, 10]
    [2, 11]
    [2, 12]
    [4, 11]
    [4, 12]
    [6, 12]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多