我想从 2 个不同的数组中获取一个新数组(名为 Result),其中:
0 _ 0 => Hold state
1 _ 0 => 1
0 _ 1 => 0
1 _ 1 => 0
例子:
array1 array2 Result
0 0 0
0 1 0
1 1 0
1 0 1
0 0 1
0 0 1
1 0 1
0 0 1
1 1 0
0 0 0
0 1 0
0 0 0
1 0 1
0 0 1
就像
Latch SR Flip Flop device唯一的区别是 1 1 => 0
我想使用 pandas 或 numpy。感谢您的帮助。我写了这个,它可以工作,但是太慢了。
def FLIP(array1, array2):
assert array1.index.equals(array2.index), 'Indices do not match'
array = pd.Series(False, dtype=bool, index=array1.index)
i = 0
while i < len(array1):
if array1[i]:
array[i] = True
for j in xrange(i, len(array2)):
if array2[j]:
array[j] = False
break
array[j] = True
i = j
i += 1
return array.fillna(value=False)
最佳答案
如果我理解正确,我们可以利用 pandas
对待 nan
的方式来处理“保持”逻辑:
def flipper(a1, a2):
res = pd.Series(index=a1.index)
res.loc[a1 == 1] = 1
res.loc[a2 == 1] = 0
res = res.ffill().fillna(0)
return res
这在您的测试用例中给出了预期的结果:
>>> df
array1 array2 Result result_computed
0 0 0 0 0
1 0 1 0 0
2 1 1 0 0
3 1 0 1 1
4 0 0 1 1
5 0 0 1 1
6 1 0 1 1
7 0 0 1 1
8 0 1 0 0
9 0 0 0 0
10 0 1 0 0
11 0 0 0 0
12 1 0 1 1
13 0 0 1 1
并且似乎与您的一般输出匹配:
from itertools import product
def check():
for w in range(1, 9):
for a0 in product(range(2), repeat=w):
for a1 in product(range(2), repeat=w):
s0, s1 = pd.Series(a0), pd.Series(a1)
flipper_result = flipper(s0, s1)
FLIP_result = FLIP(s0, s1)
assert (flipper_result == FLIP_result).all()
return True
>>> check()
True
关于python - 使用 2 个不同的数组和 python 拖动值(simil 触发器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29541278/