小编Ash*_*osh的帖子

查找提供的Sum值的组合

我有这样的一系列数字

myvar = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186]
Run Code Online (Sandbox Code Playgroud)

现在我想计算所有这些可能的组合(长度为1到20),其总和等于给定的数字m.

我尝试使用以下代码解决:

def sum_count(m):    ## Where m is the sum required

    from itertools import combinations

    myseq = []
    for i in range(1,len(myvar)):
        mycomb = list(combinations(mass,i));  # Getting combinations of length i
        mycomb = [list(j) for j in mycomb];
        for j in range(len(mycomb)-1,-1,-1):
            if sum(mycomb[j]) == m:
                myseq.append(mycomb[j])

    return(myseq)
Run Code Online (Sandbox Code Playgroud)

当我放m = 270(例如)它给我:

[[114, 156], [57, 99, …
Run Code Online (Sandbox Code Playgroud)

python combinations function

5
推荐指数
2
解决办法
4447
查看次数

如何在任意顺序中找到多个pandas数据帧中的一对列的交集?

我有多个pandas数据帧,为了保持简单,让我说我有三个.

   >> df1=
       col1  col2
   id1  A     B  
   id2  C     D  
   id3  B     A  
   id4  E     F  


    >> df2=
       col1  col2
   id1  B     A  
   id2  D     C  
   id3  M     N  
   id4  F     E  

    >> df3=
       col1  col2
   id1  A     B  
   id2  D     C  
   id3  N     M  
   id4  E     F  
Run Code Online (Sandbox Code Playgroud)

需要的结果是:

    >> df=
       col1  col2
   id1  A     B
   id2  C     D
   id3  E     F
Run Code Online (Sandbox Code Playgroud)

因为对(A,B),(C,D),(E,F)出现在所有数据帧中,尽管它可以颠倒.

使用pandas merge时,只考虑列的传递方式.为了检查我的观察,我尝试了两个数据框的以下代码:

df1['reverse_1'] = (df1.col1+df1.col2).isin(df2.col1 + df2.col2)

df1['reverse_2'] = (df1.col1+df1.col2).isin(df2.col2 + df2.col1)
Run Code Online (Sandbox Code Playgroud)

我发现结果不同:

col1    col2    reverse_1 …
Run Code Online (Sandbox Code Playgroud)

python dataframe python-3.x pandas

2
推荐指数
1
解决办法
466
查看次数

标签 统计

python ×2

combinations ×1

dataframe ×1

function ×1

pandas ×1

python-3.x ×1