# Permute values pandas dataframe

I have a dataframe with name of persons in the index and name of fruits in columns, and the values are the distance from person to fruit. Like this

``````(index)   apple  orange  lemon  grape
John      22.3   13.1    14.9   8.8
Mike      12.1   14.2    11.3   5.3
Kevin     9.13   14.9    3.3    22.3
Leon      11.9   13.2    7.14   21.1
Joe       1.15   23.12   11.11  3.18
Frank     4.13   4.13    3.12   29.3
Ralph     7.8    23.1    14.4   29.0
``````

A person only can pick one fruit and I need to find the overall lowest distance (so i need to sum the total distance of all the combinations and fint the lowest) and the name of the person that is picking each fruit.

THe best way to solve this is using itertools.permutation?

Assuming that you need each fruit to be picked by a different person, you can use `itertools`皇冠hg0088代理网址 to evaluate all possible combinations of name and fruit, but this will be intractable for larger problems.

A typical solution is to use . Python has many libraries that can help you solving IP problems. For example, below is a solution to you problem using the library:

``````import numpy as np
import pandas as pd
import cvxpy as cp
from io import StringIO

data = """name   apple  orange  lemon  grape
John      22.3   13.1    14.9   8.8
Mike      12.1   14.2    11.3   5.3
Kevin     9.13   14.9    3.3    22.3
Leon      11.9   13.2    7.14   21.1
Joe       1.15   23.12   11.11  3.18
Frank     4.13   4.13    3.12   29.3
Ralph     7.8    23.1    14.4   29.0"""

# Define the decision variable as a matrix of boolean values with
# len(names) rows and len(fruits) columns
x = cp.Variable(shape=(len(df.index), len(df.columns)), boolean=True)

# Define the objective function as the sum distances
objective = cp.sum(cp.multiply(df.values, x))

# Constrain the problem so that each person picks a single fruit
# and each fruit is picked by someone
constraint1 = cp.sum(x, axis=0) == 1
constraint2 = cp.sum(x, axis=1) <= 1

# Define the problem and fins solution
problem = cp.Problem(cp.Minimize(objective), [constraint1, constraint2])
problem.solve()
``````

``````>>> x.value.round()
array([[0., 0., 0., 0.],
[0., 0., 0., 1.],
[0., 0., 1., 0.],
[0., 0., 0., 0.],
[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 0., 0.]])
``````

Meaning that Joe picks the apple, Frank picks the orange, Kevin picks the lemon, and Mike picks the grape.