数据框最大匹配两列

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

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函数:

from scipy.optimize import linear_sum_assignment

tmp = pd.crosstab(df['X'], df['Y'])

idx, col = linear_sum_assignment(tmp, maximize=True)

out = pd.DataFrame({'X': tmp.index[idx], 'Y': tmp.columns[col]})

输出结果:

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

中间的交叉表 (tmp):

Y  a  b  c  d  e
X               
1  1  1  0  0  0
2  0  0  1  1  0
3  1  1  0  0  0
4  0  0  1  1  1
5  0  0  1  0  1
另一个例子
# df: 这里我们移除了 3/b 和 5/e 对
   X  Y
0  1  a
1  1  b
2  2  c
3  2  d
4  3  a
5  4  c
6  4  d
7  4  e
8  5  c

# out
   X  Y
0  1  b
1  2  d
2  3  a
3  4  e
4  5  c
英文:

I would use a linear_sum_assignment on the crosstab:

from scipy.optimize import linear_sum_assignment

tmp = pd.crosstab(df['X'], df['Y'])

idx, col = linear_sum_assignment(tmp, maximize=True)

out = pd.DataFrame({'X': tmp.index[idx], 'Y': tmp.columns[col]})

Output:

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

Intermediate crosstab (tmp):

Y  a  b  c  d  e
X               
1  1  1  0  0  0
2  0  0  1  1  0
3  1  1  0  0  0
4  0  0  1  1  1
5  0  0  1  0  1
other example
# df: here we removed the 3/b and 5/e pairs
   X  Y
0  1  a
1  1  b
2  2  c
3  2  d
4  3  a
5  4  c
6  4  d
7  4  e
8  5  c

# out
   X  Y
0  1  b
1  2  d
2  3  a
3  4  e
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:

确定