Python中字符串数组的逻辑操作

Python中字符串数组的逻辑操作,python,string,numpy,logical-operators,Python,String,Numpy,Logical Operators,我知道以下逻辑操作适用于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',

我知道以下逻辑操作适用于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(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')

“我仍然使用某种循环(与numpy解决方案相同),但它隐藏在简明的列表理解中。”-通常,在使用numpy时,您希望循环发生在C中,而不是列表理解中。C循环可以避免大量开销。Python循环通常要慢几十到几千倍。@user2357112老实说,我不清楚OP使用numpy是因为他真的需要强大的线性代数工具箱,还是因为这是他知道的执行分段运算的唯一方法。将字符串存储在numpy数组中是非常特殊的,它不像你用它做矩阵向量乘法。。。我只是提供了一个不必使用numpy的替代方案。请随意投赞成票或反对票。
In [306]: B[~A]=''
In [307]: B
Out[307]: 
array(['eggs', '', 'cheese'], 
      dtype='<U6')