【发布时间】:2019-02-07 17:57:36
【问题描述】:
So I have a dataframe representing various model estimates for the likelihood of each of a group of candidates winning an election.
Steve John
Model1 0.327586 0.289474
Model2 0.322581 0.285714
Model3 0.303030 0.294118
我想要一个数据框来表示跨列的模型值的所有组合,即所有列的笛卡尔积。所以上面会变成下面。
model Steve value Steve model John value John
0 Model1 0.327586 Model1 0.289474
1 Model1 0.327586 Model2 0.285714
2 Model1 0.327586 Model3 0.294118
3 Model2 0.322581 Model1 0.289474
4 Model2 0.322581 Model2 0.285714
5 Model2 0.322581 Model3 0.294118
6 Model3 0.303030 Model1 0.289474
7 Model3 0.303030 Model2 0.285714
8 Model3 0.303030 Model3 0.294118
以上是简单的情况,但理论上我希望能够对 N 个模型和 M 个候选者执行此操作,从而产生一个具有 N^M 行和 2M 列的数据框(实际上 N
在寻找答案时,我看到了很多关于 itertools 模块的建议,但无法弄清楚如何跨多个列表获取所有组合(itertools.combinations 似乎只有查找单个列表中的所有组合)。
【问题讨论】:
-
那么只需要2列的解决方案吗?所以请从您的问题中删除
I would like to be able to do this for N models and M canditates,因为接受的答案仅适用于2 columns。还是缺少什么? -
你的意思是Cartesian-product。我添加了那个标签。
标签: pandas combinations combinatorics cartesian-product