我是 Python 的新手,看起来它具有很大的灵 active 并且比传统的 RDBMS 系统更快。
致力于一个非常简单的过程来创建随机的幻想团队。我来自 RDBMS 背景 (Oracle SQL),这似乎不是这种数据处理的最佳选择。
我使用从 csv 文件读取的 pandas 制作了一个数据框,现在有一个包含两列的简单数据框 -- 球员,薪水:
` Name Salary
0 Jason Day 11700
1 Dustin Johnson 11600
2 Rory McIlroy 11400
3 Jordan Spieth 11100
4 Henrik Stenson 10500
5 Phil Mickelson 10200
6 Justin Rose 9800
7 Adam Scott 9600
8 Sergio Garcia 9400
9 Rickie Fowler 9200`
我试图通过 python (pandas) 做的是产生 6 名球员的所有组合,薪水在一定数量 45000 到 50000 之间。
在查找 python 选项时,我发现 itertools 组合很有趣,但它会产生大量组合,而不会过滤薪水总和。
在传统的 SQL 中,我会使用 SUM 进行大量合并笛卡尔连接,但随后我会在不同的位置获取玩家。
如A、B、C则C、B、A..
我的传统 SQL 不能很好地工作是这样的:
` SELECT distinct
ONE.name AS "1",
TWO.name AS "2",
THREE.name AS "3",
FOUR.name AS "4",
FIVE.name AS "5",
SIX.name AS "6",
sum(one.salary + two.salary + three.salary + four.salary + five.salary + six.salary) as salary
FROM
nl.pgachamp2 ONE,nl.pgachamp2 TWO,nl.pgachamp2 THREE, nl.pgachamp2 FOUR,nl.pgachamp2 FIVE,nl.pgachamp2 SIX
where ONE.name != TWO.name
and ONE.name != THREE.name
and one.name != four.name
and one.name != five.name
and TWO.name != THREE.name
and TWO.name != four.name
and two.name != five.name
and TWO.name != six.name
and THREE.name != four.name
and THREE.name != five.name
and three.name != six.name
and five.name != six.name
and four.name != six.name
and four.name != five.name
and one.name != six.name
group by ONE.name, TWO.name, THREE.name, FOUR.name, FIVE.name, SIX.name`
有没有办法在 Pandas/Python 中做到这一点?
任何可以指向的文档都很棒!
最佳答案
我针对 6 个组合运行此程序,但没有找到满意的团队。我改用 5。
这应该让你到达那里:
from itertools import combinations
import pandas as pd
s = df.set_index('Name').squeeze()
combos = pd.DataFrame([c for c in combinations(s.index, 5)])
combo_salary = combos.apply(lambda x: s.ix[x].sum(), axis=1)
combos[(combo_salary >= 45000) & (combo_salary <= 50000)]
关于Python Pandas self join 用于合并笛卡尔积以产生所有组合和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38636460/