【问题标题】:Pairwise combinations of pandas columnspandas 列的成对组合
【发布时间】:2021-04-19 17:31:21
【问题描述】:

我有一个包含大量列的 pandas 数据框,我想生成满足特定条件的列的成对计数。给定这样的数据框:

df = pd.DataFrame({'A':['foo','foo','bar','bar'],
'B':['foo','foo','foo','bar'],
'C':['foo','bar','foo','bar'],
'D':['foo','foo','foo','foo'],
'E':['bar','bar','bar','bar']})

我想创建一个函数来告诉我,例如,对于每个列组合,两列都是“foo”的行数。我可以用这样的循环方法来做到这一点:

def pairwise_crit_count(df,crit):
    # define column list
    col_list = df.columns
    # initialize dict that will turn into a pd frame for the result
    result_dict = {'row':col_list}
    for first_col in col_list:
        # create empty list that will become the column of result
        temp_list = []
        for second_col in col_list:
            # count the number of rows that meet the criteria
            num = df.loc[(df[first_col]==crit) & (df[second_col]==crit)].shape[0]
            temp_list.append(num)
        # add to result dict
        result_dict[first_col] = temp_list
    return pd.DataFrame(result_dict)

pairwise_crit_count(df,'foo')

但我觉得我缺少一个更清洁的解决方案。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    在这种情况下,共现均值矩阵乘法:

    s = df.eq('foo').astype(int)
    out = s.T @ s
    

    输出:

       A  B  C  D  E
    A  2  2  1  2  0
    B  2  3  2  3  0
    C  1  2  2  2  0
    D  2  3  2  4  0
    E  0  0  0  0  0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 2015-12-28
      • 2018-07-01
      • 2017-04-07
      • 2021-10-04
      相关资源
      最近更新 更多