Numpy Remove duplicates, apply function, then add it back

Viewed 85

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

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.

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]
Related