我们有一个包含重复项的数组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 ]
虽然有点奇怪...
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
与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]
正在处理元素方式。