2

We have an array x containing duplicates and a function f() that only accepts a 1-D array without duplicates. We need the results of f(x) as if the function can accept duplicate values.

If we had removed the duplicate values before passing it into the function, how can we add duplicated results to the array return by the function?

import numpy as np

def f(x):
    ''' assume this function cannot accept duplicates '''
    return -1 * x

x = np.array([1, 3, 5, 7, 7, 9, 9, 9, 11, 13, 13, 15, 17, 17, 19, 21, 21, 21, 23])
y = f(np.unique(x))

print(y)    # [ -1 -3 -5 -7 -9 -11 -13 -15 -17 -19 -21 -23 

# Needed: [ -1 -3 -5 -7 -7 -9 -9 -9 -11 -13 -13 -15 -17 -17 -19 -21 -21 -21 -23 ]

2 Answers 2

2

Approach #1

Use return_inverse argument with it -

unq, tags  = np.unique(x, return_inverse=True)
out = f(unq)[tags]

Approach #2

We can skip the sorting with np.unique using pandas.factorize instead for perf. boost -

import pandas as pd

tags, unq = pd.factorize(x)
out = f(unq)[tags]

Assumption is that f is working on an elementwise-manner.

Sign up to request clarification or add additional context in comments.

Comments

0

Although a bit strange...

import numpy as np

def f(X):
    return -1 * x

x = np.array([1, 3, 5, 7, 7, 9, 9, 9, 11, 13, 13, 15, 17, 17, 19, 21, 21, 21, 23])
y = f(np.unique(x))

print(y)

Output:

[ -1  -3  -5  -7  -7  -9  -9  -9 -11 -13 -13 -15 -17 -17 -19 -21 -21 -21 -23]

10 Comments

I am not getting that y. Are you sure you printing the y from your code?
Yes. Try copying and pasting the whole thing.
Your f has wrong syntax. It should be def f(x):. There's typo.
You have def f(X):. Why are using x and not X inside the function?
With def f(X): return -1 * x, it's picking x from globals(), not the function argument, which has X. I am assuming you are noticing the difference between X and x. f(np.unique(x)) is not supposed to work as OP showed in the question. Making a typo just to show an expected output isn't a solution.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.