Python 中字符串数组的逻辑运算

Logical operations with array of strings in Python

我知道以下逻辑运算适用于 numpy:

A = np.array([True, False, True])
B = np.array([1.0, 2.0, 3.0])
C = A*B = array([1.0, 0.0, 3.0])

但如果 B 是字符串数组,情况就不一样了。是否可以执行以下操作:

A = np.array([True, False, True])
B = np.array(['eggs', 'milk', 'cheese'])
C = A*B = array(['eggs', '', 'cheese'])

那是一个字符串乘以 False 应该等于一个空字符串。可以在 Python 中不使用循环来完成吗(不必使用 numpy)?

谢谢!

您可以使用 np.where 基于掩码进行此类选择 -

np.where(A,B,'')

样本运行-

In [4]: A
Out[4]: array([ True, False,  True], dtype=bool)

In [5]: B
Out[5]: 
array(['eggs', 'milk', 'cheese'], 
      dtype='|S6')

In [6]: np.where(A,B,'')
Out[6]: 
array(['eggs', '', 'cheese'], 
      dtype='|S6')

因为字符串可以乘以整数,而布尔值是整数:

A = [True, False, True]
B = ['eggs', 'milk', 'cheese']
C = [a*b for a, b in zip(A, B)]
# C = ['eggs', '', 'cheese']

我仍然使用某种循环(与 numpy 解决方案相同),但它隐藏在简洁的列表理解中。

或者:

C = [a if b else '' for a, b in zip(A, B)]  # explicit loop may be clearer than multiply-sequence trick

np.char 将字符串方法应用于数组元素:

In [301]: np.char.multiply(B, A.astype(int))
Out[301]: 
array(['eggs', '', 'cheese'], 
      dtype='<U6')

我不得不将布尔值转换为整数,并将其放在第二位。

其他问题中的时间表明 np.char 迭代并应用了 Python 方法。速度与列表理解大致相同。

对于就地更改,使用掩码赋值而不是 where

In [306]: B[~A]=''
In [307]: B
Out[307]: 
array(['eggs', '', 'cheese'], 
      dtype='<U6')