我有两个相同尺寸的 x 和 y 数组。我想在这些数组中进行多个比较(或运算符)值,并生成具有相同维度的新数组。新数组应该具有我指定的值。以下是我要做的事情的小小示范: -
stderr
我可以比较多个语句并生成新数组。但是,我想用值10替换True。所以当我尝试这一行时,它给了我一个错误: -
import contextlib, sys
@contextlib.contextmanager
def log_print(file):
# capture all outputs to a log file while still printing it
class Logger:
def __init__(self, file):
self.terminal = sys.stdout
self.log = file
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def __getattr__(self, attr):
return getattr(self.terminal, attr)
logger = Logger(file)
_stdout = sys.stdout
_stderr = sys.stderr
sys.stdout = logger
sys.stderr = logger
try:
yield logger.log
finally:
sys.stdout = _stdout
sys.stderr = _stderr
with log_print(open('mylogfile.log', 'w')):
print('hello world')
print('hello world on stderr', file=sys.stderr)
# you can capture the output to a string with:
# with log_print(io.StringIO()) as log:
# ....
# print('[captured output]', log.getvalue())
我期待的是: -
In [1]: import numpy
In [2]: import numpy as np
In [3]: x = np.array([5, 2, 3, 1, 4, 5])
In [4]: y = np.array([2, 3, 3, 8, 8, 6])
In [5]: result_array = [y > 3] or [x < 5]
In [6]: print(result_array)
[array([False, False, False, True, True, True], dtype=bool)]
感谢任何帮助
答案 0 :(得分:1)
您需要将结果转换为整数才能看到1
:
x = np.array([5, 2, 3, 1, 4, 5])
y = np.array([2, 3, 3, 8, 8, 6])
result_array = np.logical_or(y > 3, x < 5)
res = result_array.astype(int)
res[result_array] = 10
print(res)
输出:
[ 0 10 10 10 10 10]
答案 1 :(得分:0)
您可以使用此功能接近您提到的结果:
import numpy as np
x = np.array([5, 2, 3, 1, 4, 5])
y = np.array([2, 3, 3, 8, 8, 6])
result_array = np.where(y > 3, 10, False)
print(result_array)
结果:
[ 0 0 0 10 10 10]
请注意,有0而不是Falses,因为它只包含数字