Python/Pandas通过一个限制获得所有可能的组合

2024-05-13 20:39:35 发布

您现在位置:Python中文网/ 问答频道 /正文

目标-我总共有50条记录,需要找到6名薪水<;=50000和>;=48000的球员的所有可能组合。你知道吗

如果我只使用了大约20条记录,但在尝试将其应用于所有50条记录时,我不断遇到内存错误,那么下面的代码就可以工作了。我正在寻找一种方法来优化我的代码,要么只接受50k以下的组合,而不可能像我一样循环。你知道吗

示例数据(目前共有50条记录)-

    ID          Salary
0   11282489    11000
1   11282517    10800
2   11282479    10700
3   11282521    10200
4   11282483    10100
5   11282481    10000

当前代码-

comb = combinations(data['ID'], 6) 
comb_list = list(comb)
df_list = []
for i in comb_list:
    i = list(i)
    if data.loc[data['ID'].isin(i)]['Salary'].sum() <= 50000 and data.loc[data['ID'].isin(i)]['Salary'].sum() >= 48000:
        df_list.append(data.loc[data['ID'].isin(i)])

    counter +=1

“组合列表”目前的结果是大约1500万个组合,这是主要问题。有没有比我现在做的更好的方法来应用薪资筛选?你知道吗

谢谢!你知道吗


Tags: 方法代码ltid目标dfdata记录
1条回答
网友
1楼 · 发布于 2024-05-13 20:39:35

你当然可以避免这种循环。你知道吗

找到所有的组合,将它们的id映射到salary,然后计算每个组合的总和。然后再把工资在48000到50000之间的组合作为子集

设置

import pandas as pd
import numpy as np
from itertools import combinations

np.random.seed(123)
df = pd.DataFrame({'ID': np.arange(1,51,1),
                   'Salary': np.random.randint(7000,12000,50)})
# ID to Salary dictionary
d = df.set_index('ID').Salary.to_dict()

代码

n = 6  # length of combination tuples

# Create df of people and their salary
df2 = pd.DataFrame(list(combinations(df.ID, n)), 
                   columns=['p'+str(i) for i in np.arange(1,n+1,1)])
df2 = pd.concat([df2, df2.replace(d).add_suffix('_salary')], axis=1)

# Subset to those within the range you care about
df2[df2[[col for col in df2.columns if '_salary' in col]].sum(1).between(48000,50000)]

输出

        p1  p2  p3  p4  p5  p6  p1_salary  p2_salary  p3_salary  p4_salary  p5_salary  p6_salary
48465    1   2   6  10  19  32      10582      10454       7096       7111       7039       7588
48481    1   2   6  10  19  48      10582      10454       7096       7111       7039       7371
209845   1   3   5   6   9  10      10582       8346       8593       7096       7942       7111
209854   1   3   5   6   9  19      10582       8346       8593       7096       7942       7039
209883   1   3   5   6   9  48      10582       8346       8593       7096       7942       7371
...

(共有188531个这样的组合)。肯定会有更有效的解决办法。你知道吗

相关问题 更多 >