数据框最大匹配两列

huangapple go评论104阅读模式
英文:

Dataframe max matching two columns

问题

我有一个数据框架,我正在寻找一种方法来找到两列中唯一匹配对的最大数。例如,如果我将数据框架限制在这两列上:

X Y
1 a
1 b
2 c
2 d
3 b
3 a
4 c
4 d
4 e
5 e
5 c

结果应该是:

X Y
1 a
2 c
3 b
4 d
5 e

因此,如果我匹配1a,那么我不能再使用1作为列X,也不能再使用a作为Y

困难的部分是要根据这个规则匹配尽可能多的对。

非常感谢。

英文:

I have a Dataframe and I am looking for a way to find the maximum number on uniquly matched pairs on two columns.
If for example I limit my Dataframe to only these two columns:

X Y
1 a
1 b
2 c
2 d
3 b
3 a
4 c
4 d
4 e
5 e
5 c

The result shoud be:

X Y
1 a
2 c
3 b
4 d
5 e

So if I match 1 & a, then I cannot use 1 for column X anymore, nor a for Y anymore.

The difficult part is to match the maximum number of pairs possible with this rule.

Many thanks.

答案1

得分: 2

我会在crosstab上使用linear_sum_assignment函数:

  1. from scipy.optimize import linear_sum_assignment
  2. tmp = pd.crosstab(df['X'], df['Y'])
  3. idx, col = linear_sum_assignment(tmp, maximize=True)
  4. out = pd.DataFrame({'X': tmp.index[idx], 'Y': tmp.columns[col]})

输出结果:

  1. X Y
  2. 0 1 a
  3. 1 2 c
  4. 2 3 b
  5. 3 4 d
  6. 4 5 e

中间的交叉表 (tmp):

  1. Y a b c d e
  2. X
  3. 1 1 1 0 0 0
  4. 2 0 0 1 1 0
  5. 3 1 1 0 0 0
  6. 4 0 0 1 1 1
  7. 5 0 0 1 0 1
另一个例子
  1. # df: 这里我们移除了 3/b 和 5/e 对
  2. X Y
  3. 0 1 a
  4. 1 1 b
  5. 2 2 c
  6. 3 2 d
  7. 4 3 a
  8. 5 4 c
  9. 6 4 d
  10. 7 4 e
  11. 8 5 c
  12. # out
  13. X Y
  14. 0 1 b
  15. 1 2 d
  16. 2 3 a
  17. 3 4 e
  18. 4 5 c
英文:

I would use a linear_sum_assignment on the crosstab:

  1. from scipy.optimize import linear_sum_assignment
  2. tmp = pd.crosstab(df['X'], df['Y'])
  3. idx, col = linear_sum_assignment(tmp, maximize=True)
  4. out = pd.DataFrame({'X': tmp.index[idx], 'Y': tmp.columns[col]})

Output:

  1. X Y
  2. 0 1 a
  3. 1 2 c
  4. 2 3 b
  5. 3 4 d
  6. 4 5 e

Intermediate crosstab (tmp):

  1. Y a b c d e
  2. X
  3. 1 1 1 0 0 0
  4. 2 0 0 1 1 0
  5. 3 1 1 0 0 0
  6. 4 0 0 1 1 1
  7. 5 0 0 1 0 1
other example
  1. # df: here we removed the 3/b and 5/e pairs
  2. X Y
  3. 0 1 a
  4. 1 1 b
  5. 2 2 c
  6. 3 2 d
  7. 4 3 a
  8. 5 4 c
  9. 6 4 d
  10. 7 4 e
  11. 8 5 c
  12. # out
  13. X Y
  14. 0 1 b
  15. 1 2 d
  16. 2 3 a
  17. 3 4 e
  18. 4 5 c

huangapple
  • 本文由 发表于 2023年7月27日 20:07:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定