Con*_*Mai 3 python matlab numpy
我一直绞尽脑汁寻找一个与这个老问题相符的解决方案.我一直在尝试找到一个复制索引结果的Python代码模式.例如:
A = [3;4;4;3;6]
B = [2;5;2;6;3;2;2;5]
[tf ix] = ismember(A,B)
>> A(tf)
ans =
3
3
6
>> B(ix(tf))
ans =
3
3
6
Run Code Online (Sandbox Code Playgroud)
这允许我做的是,如果有一个数组C的排序方式与BI现在可以适当地将C的值插入到一个新的数组D中,该数组D的排序方式与A相同.我做了很多数据映射!我希望这能用于各种数据类型,特别是字符串和日期时间.看起来numpy的in1d让我在那里走了一半.我也对其他Pythonic想法持开放态度!
D(tf) = C(ix(tf))
Run Code Online (Sandbox Code Playgroud)
谢谢!
import numpy as np
A = np.array([3,4,4,3,6])
B = np.array([2,5,2,6,3,6,2,2,5])
def ismember(a, b):
# tf = np.in1d(a,b) # for newer versions of numpy
tf = np.array([i in b for i in a])
u = np.unique(a[tf])
index = np.array([(np.where(b == i))[0][-1] if t else 0 for i,t in zip(a,tf)])
return tf, index
tf,ix=ismember(A,B)
print(tf)
# [ True False False True True]
print(ix)
# [4 0 0 4 5]
print(A[tf])
# [3 3 6]
print(B[ix[tf]])
# [3 3 6]
Run Code Online (Sandbox Code Playgroud)