Numpy删除重复项,应用函数,然后将其添加回去

问题描述 投票:1回答:2

我们有一个包含重复项的数组x和一个仅接受一维数组但没有重复项的函数f()。我们需要f(x)的结果,就好像该函数可以接受重复的值。

如果我们在将重复的值传递给函数之前已经删除了重复的值,如何将重复的结果添加到函数返回的数组中?

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 ]

python python-3.x numpy numpy-ndarray
2个回答
1
投票

虽然有点奇怪...

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)

输出:

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

1
投票

方法#1

return_inverse参数一起使用-

return_inverse

方法#2

我们可以使用unq, tags = np.unique(x, return_inverse=True) out = f(unq)[tags] 代替perf来跳过np.unique的排序。提升-

pandas.factorize

假设是import pandas as pd tags, unq = pd.factorize(x) out = f(unq)[tags] 正在处理元素方式。

© www.soinside.com 2019 - 2024. All rights reserved.