使用偶数和奇数格式化 Numpy 数组
Formatting a Numpy array with even and odd numbers
我正在尝试编写一个代码,将 sequence_numbers
中的偶数替换为正 init_val
值,并将每个奇数和 0 值变量替换为负 init_val
值。我怎么能编写这样的代码?
代码:
import numpy as np
import pandas as pd
sequence_numbers= np.array([1,0,4,7,9,12,15,16,22,2,4,8,11,13,11,21,23,3])
#The choice could be 'even', 'odd' or '0'
choice = 'even'
init_val = 100
预期输出:
[-100, -100, 100, -100, -100, 100, -100,100, 100,
100, 100, 100, -100, -100, -100, -100, -100, -100 ]
使用 numpy.where
和模运算符确定 odd/even 状态。
'even' 示例:
out = np.where(sequence_numbers%2, -init_val, init_val)
输出:
array([-100, 100, 100, -100, -100, 100, -100, 100, 100, 100, 100,
100, -100, -100, -100, -100, -100, -100])
对于'odd',只需反转True/False值:
out = np.where(sequence_numbers%2, init_val, -init_val)
或反转init_val
:
if choice == 'odd':
init_val *= -1
out = np.where(sequence_numbers%2, -init_val, init_val)
您可以使用:
out = (sequence_numbers % 2 * -2 + 1) * init_val
print(out)
# Output
array([-100, 100, 100, -100, -100, 100, -100, 100, 100, 100, 100,
100, -100, -100, -100, -100, -100, -100])
我正在尝试编写一个代码,将 sequence_numbers
中的偶数替换为正 init_val
值,并将每个奇数和 0 值变量替换为负 init_val
值。我怎么能编写这样的代码?
代码:
import numpy as np
import pandas as pd
sequence_numbers= np.array([1,0,4,7,9,12,15,16,22,2,4,8,11,13,11,21,23,3])
#The choice could be 'even', 'odd' or '0'
choice = 'even'
init_val = 100
预期输出:
[-100, -100, 100, -100, -100, 100, -100,100, 100,
100, 100, 100, -100, -100, -100, -100, -100, -100 ]
使用 numpy.where
和模运算符确定 odd/even 状态。
'even' 示例:
out = np.where(sequence_numbers%2, -init_val, init_val)
输出:
array([-100, 100, 100, -100, -100, 100, -100, 100, 100, 100, 100,
100, -100, -100, -100, -100, -100, -100])
对于'odd',只需反转True/False值:
out = np.where(sequence_numbers%2, init_val, -init_val)
或反转init_val
:
if choice == 'odd':
init_val *= -1
out = np.where(sequence_numbers%2, -init_val, init_val)
您可以使用:
out = (sequence_numbers % 2 * -2 + 1) * init_val
print(out)
# Output
array([-100, 100, 100, -100, -100, 100, -100, 100, 100, 100, 100,
100, -100, -100, -100, -100, -100, -100])