Home > Mobile >  Is there a function that outputs a max value of Y for the same Xs?
Is there a function that outputs a max value of Y for the same Xs?

Time:02-21

I am stuck trying to solve that task, so if you have any suggestion, it's extremely appreciated. Suppose we have two sets:

  • X = [0, 1.0, 1.0, 3.0, 4.0, 4.0, 3.0, 3.0, 5.0]
  • Y = [0, 0.2, 0.1, 0.3, 1.0, 0.9, 0.7, 0.4, 0.0]

So, that Y = f(X). Each element of X corresponds to the one, that is below. Can I make it so that each element of X corresponds to only one element of Y? And a program has to use MAX operator in order to choose one of the alternative elements.

  • X = [0, 1.0, 3.0, 4.0, 5.0]
  • Y = [0, 0.2, 0.7, 1.0, 0.0]

CodePudding user response:

You do not necessarily need numpy here.

In pure python, you can sort the pairs with sorted, then feed to dict to eliminate the duplicate X (keeping the last = max Y), then split again in two:

X2, Y2 = zip(*dict(sorted(zip(X,Y))).items())

As lists:

X2, Y2 = map(list, zip(*dict(sorted(zip(X,Y))).items()))

output:

X2
# [0, 1.0, 3.0, 4.0, 5.0]

Y2
# [0, 0.2, 0.7, 1.0, 0.0]

CodePudding user response:

Using pandas

X, Y = map(list, zip(*pd.Series(index=X, data=Y).max(level=0).items()))

Or:

s = pd.Series(index=X, data=Y).max(level=0)
X, Y = s.index.tolist(), s.tolist()

CodePudding user response:

To avoid sorting, you could use a dictionary to hold the maximum Y for each X and then break it back down into two lists.

X = [0, 1.0, 1.0, 3.0, 4.0, 4.0, 3.0, 3.0, 5.0]
Y = [0, 0.2, 0.1, 0.3, 1.0, 0.9, 0.7, 0.4, 0.0]

XY = dict()
XY.update((x,max(y,XY.get(x,y))) for x,y in zip(X,Y))

X,Y = map(list,zip(*XY.items()))

print(X)
print(Y)
[0, 1.0, 3.0, 4.0, 5.0]
[0, 0.2, 0.7, 1.0, 0.0]
  • Related