如何解决使用python查找具有条件逻辑的组合
我正在尝试解决一个优化问题,我从数据框中获取名称列表(每行包含附加信息),找到满足某些约束的组合列表。说明这一点的最佳方式是使用每日梦幻高尔夫数据:
https://docs.google.com/spreadsheets/d/1tLHORoavhIQ7p4I6rHPuOU3GbJgxSp_O__wZLAaNQvc/edit?usp=sharing 更新: 我想要做的是找到玩家名称的不同组合(组合大小为 6,从最多可达到 60 的列表中)。 需要注意的是,我只想保留这两个约束的组合:
- 6名球员的工资总和为
- 'score' 大于 3 但小于 7
我的方法是 1. 找到组合,然后 2. 过滤输出,但这需要几分钟才能完成。我的问题是是否有比下面的代码更理想的方法来创建我想要的组合。谢谢
import numpy as np
import pandas as pd
from itertools import combinations as comb
#get the data im working with from google sheets
file = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vS-bxUEIkfCNr_HBDnattVnjsBfudPc9ECckD80IRYlZr9tcwpyB2mvRkhw6ZFj57ijDt4JH_3k8zSs/pub?gid=0&single=true&output=csv'
df = pd.read_csv(file)
#get the columns I need and drop the empty rows
playersdf = df[['Player','Salary','Avg','score']].dropna(how='any').set_index('Name')
playersdf['Salary'] = playersdf['Salary'].str.replace(',','').astype('int32')
#creating new df to wrap it all together and avoid the save with copy warnings
combos = pd.DataFrame()
lineups = pd.DataFrame()
#create the combinations of size 2 and convert to lists
favs = comb(playersdf.index.tolist(),6)
i = 1
#loop through the combos and find the ones we want and aggregating the details behind those combinations
for item in favs:
combo = playersdf[playersdf.index.isin(item)]
if ((combo['score'].sum()>=3) & (combo['score'].sum()<=7)):
combos = combo.copy()
combos['ComboNumber']=i
combos['score Total'] = combo['score'].sum()
combos['Salary Total'] = combo['Salary'].sum()
combos['Lineup'] = str(item)
i+=1
#add the combos we want to a dataframe if even
lineups = pd.concat([combos,lineups],ignore_index=False,sort=False)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。