Skip to main content
 首页 » 编程设计

python之带有字符数组的 Numpy ufunc.at

2024年11月24日8findumars

有没有办法使用 numpy ufunc.at(特别是 add.at)来连接字符串数组? add.at 或 char.add.at 都不能用于字符串/字符数组。

该方法需要处理n维数组,所以先根据索引拆分再join不太理想

a = np.array(['a', 'b']) 
ixs =  np.array([0, 1, 1]) 
vals = np.array(['e', 'f', 'g]) 
 
# Neither of these options work 
 
np.add.at(a, ixs, vals) 
 
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-29-fb8e3bd48930> in <module>() 
      2 ixs =  np.array([0, 1]) 
      3 vals = np.array(['e', 'e']) 
----> 4 np.add.at(a, ixs, vals) 
 
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1') 
 
 
 
np.char.add.at(a, ixs, vals) 
 
--------------------------------------------------------------------------- 
AttributeError                            Traceback (most recent call last) 
<ipython-input-30-e1bb1f7868dd> in <module>() 
      2 ixs =  np.array([0, 1]) 
      3 vals = np.array(['e', 'e']) 
----> 4 np.char.add.at(a, ixs, vals) 
 
AttributeError: 'function' object has no attribute 'at' 
 
 

期望的输出:['ae', 'bfg']

非常感谢!

请您参考如下方法:

In [279]: a = np.array(['a', 'b'])  
     ...: ixs =  np.array([0, 1, 1])  
     ...: vals = np.array(['e', 'f', 'g'])  
     ...:                       

你的错误:

In [280]: np.char.add.at(a, ixs, vals)                                        
--------------------------------------------------------------------------- 
AttributeError                            Traceback (most recent call last) 
<ipython-input-280-f06ad4d86cfb> in <module> 
----> 1 np.char.add.at(a, ixs, vals) 
 
AttributeError: 'function' object has no attribute 'at' 
 
In [281]: np.add.at(a, ixs, vals)                                             
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-281-683423808141> in <module> 
----> 1 np.add.at(a, ixs, vals) 
 
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1') 

但让我们尝试使用对象数据类型数组add.at。

In [282]: ao=a.astype(object)                                                 
In [283]: ao                                                                  
Out[283]: array(['a', 'b'], dtype=object) 
In [284]: vo=vals.astype(object)                                              
In [285]: vo                                                                  
Out[285]: array(['e', 'f', 'g'], dtype=object) 
In [286]: np.add.at(ao, ixs, vo)                                                                                                                 
In [287]: ao                                                                  
Out[287]: array(['ae', 'bfg'], dtype=object) 

numpy ufuncs 倾向于(总是?)通过将操作委托(delegate)给对象的相应方法来操作对象 dtype 数组。 add 是为 Python 字符串定义的,因此 add.at 可以按需要工作。