在 numpy nd 数组中附加后缀时出现数据类型错误
Data Type error while appending suffix in numpy nd array
x=np.array([['A',1,'Q'],['B',2,'W'],['B',3,'E'],['C',4,'R']])
x 是一个 numpy 数组。我正在尝试以下操作,但它给了我错误
x[x[:,0]=='B',0] = x[x[:,0]=='B',0] + 'V'
UFuncTypeError: ufunc 'add' did not contain a loop with signature
matching types (dtype('<U11'), dtype('<U1')) -> None
我正在尝试在 col1 中附加一些后缀,其中我的条件在行中为真。
请帮忙
谢谢,
丽娃
In [841]: x=np.array([['A',1,'Q'],['B',2,'W'],['B',3,'E'],['C',4,'R']])
In [842]: x
Out[842]:
array([['A', '1', 'Q'],
['B', '2', 'W'],
['B', '3', 'E'],
['C', '4', 'R']], dtype='<U21')
In [843]: mask = x[:,0]=='B'
In [844]: mask
Out[844]: array([False, True, True, False])
In [845]: x[mask,0]
Out[845]: array(['B', 'B'], dtype='<U21')
np.char
具有可以将 Python 字符串方法应用于数组的函数:
In [846]: np.char.add(x[mask,0],'V')
Out[846]: array(['BV', 'BV'], dtype='<U22')
In [847]: x[mask,0]=_
In [848]: x
Out[848]:
array([['A', '1', 'Q'],
['BV', '2', 'W'],
['BV', '3', 'E'],
['C', '4', 'R']], dtype='<U21')
或者我们可以创建一个对象数据类型数组,其中包含 Python 个字符串。
In [849]: X = x.astype(object)
In [850]: X
Out[850]:
array([['A', '1', 'Q'],
['BV', '2', 'W'],
['BV', '3', 'E'],
['C', '4', 'R']], dtype=object)
In [851]: X[mask,0]
Out[851]: array(['BV', 'BV'], dtype=object)
In [852]: X[mask,0]+'V' # string plus works here
Out[852]: array(['BVV', 'BVV'], dtype=object)
x=np.array([['A',1,'Q'],['B',2,'W'],['B',3,'E'],['C',4,'R']])
x 是一个 numpy 数组。我正在尝试以下操作,但它给了我错误
x[x[:,0]=='B',0] = x[x[:,0]=='B',0] + 'V'
UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U11'), dtype('<U1')) -> None
我正在尝试在 col1 中附加一些后缀,其中我的条件在行中为真。
请帮忙
谢谢, 丽娃
In [841]: x=np.array([['A',1,'Q'],['B',2,'W'],['B',3,'E'],['C',4,'R']])
In [842]: x
Out[842]:
array([['A', '1', 'Q'],
['B', '2', 'W'],
['B', '3', 'E'],
['C', '4', 'R']], dtype='<U21')
In [843]: mask = x[:,0]=='B'
In [844]: mask
Out[844]: array([False, True, True, False])
In [845]: x[mask,0]
Out[845]: array(['B', 'B'], dtype='<U21')
np.char
具有可以将 Python 字符串方法应用于数组的函数:
In [846]: np.char.add(x[mask,0],'V')
Out[846]: array(['BV', 'BV'], dtype='<U22')
In [847]: x[mask,0]=_
In [848]: x
Out[848]:
array([['A', '1', 'Q'],
['BV', '2', 'W'],
['BV', '3', 'E'],
['C', '4', 'R']], dtype='<U21')
或者我们可以创建一个对象数据类型数组,其中包含 Python 个字符串。
In [849]: X = x.astype(object)
In [850]: X
Out[850]:
array([['A', '1', 'Q'],
['BV', '2', 'W'],
['BV', '3', 'E'],
['C', '4', 'R']], dtype=object)
In [851]: X[mask,0]
Out[851]: array(['BV', 'BV'], dtype=object)
In [852]: X[mask,0]+'V' # string plus works here
Out[852]: array(['BVV', 'BVV'], dtype=object)