对字符串使用“if”,并使用“按位and”或“逻辑and”

2024-10-03 00:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查数据集第二列中的字符串是disk、tabel还是其他任何东西。你知道吗

这是一个名为X的数据集示例:

16  disk    11  10.29   4.63    30.22 
79  table   11  20.49   60.60   20.22 
17  disk    11  22.17   0.71    10.37 

我使用了以下代码:

def featureMaking(X):

   if  (X[1]=='disk'):            
       print('It is in disk group')
   elif np.logical_or(X[1]=='table', X[1]=='chair'):
       print('table or chair')
   else: 
       print('others')

错误是:

 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我换了elifnp.u或(X[1]=='桌子',X[1]=='椅子'):到elif(X[1]=='桌子'| | X[1]=='椅子'):但存在错误。你能指导我解决这个问题吗?你知道吗

即使我忽略了eflif并且我把代码改为:

def featureMaking(X):

if  (X[1]=='disk'):            
     print('It is in disk group')

else: 
    print('others')

但我也有同样的错误!!!你知道吗


Tags: or代码inifisdef错误table
2条回答

给出:

>>> a
array([['16', 'disk', '11', '10.29', '4.63', '30.22'],
       ['79', 'table', '11', '20.49', '60.60', '20.22'],
       ['17', 'disk', '11', '22.17', '0.71', '10.37']], 
      dtype='|S5')

您可以使用np.where

>>> rows, cols=np.where(a=='disk')
>>> a[rows]
array([['16', 'disk', '11', '10.29', '4.63', '30.22'],
       ['17', 'disk', '11', '22.17', '0.71', '10.37']], 
      dtype='|S5')

或:

>>> rows, cols=np.where(a=='table')
>>> a[rows]
array([['79', 'table', '11', '20.49', '60.60', '20.22']], 
      dtype='|S5')

X[1]是二维numpy.ndarrayX的第二行。如果需要第二行的第二列,请以X[1,1]的形式访问它。你知道吗

相关问题 更多 >