提问人:Mackie Messer 提问时间:11/6/2023 最后编辑:Mackie Messer 更新时间:11/7/2023 访问量:48
使用 char 操作的 numpy reduce。
Numpy reduce with char operations
问:
我想要一种矢量化的方式来做:
numpy.char.add.reduce(["string_", values.astype("U"), "_string"], axis=0)
因此,例如,我可能想发送到 .但是,将具有任意形状,并且可能很大。[0.1, 0.2, 0.3]
["string_0.1_string", "string_0.2_string", "string_0.3_string"]
values
但是,这似乎不是一个ufunc,而且不能只是做.numpy.char.add
numpy.char.add.reduce
是否有有据可查的解决方法,或者我需要做一些聪明的事情?
答:
1赞
hpaulj
11/7/2023
#1
您的样品列表/阵列:
In [71]: x=[0.1, 0.2, 0.3]; xx = np.array(x,'U5');xx
Out[71]: array(['0.1', '0.2', '0.3'], dtype='<U5')
从文档中可以清楚地看出,不是.它只是相关字符串方法的浅层包装器。char.add
ufunc
但是我们可以链接 ,就像我们做 ''string_'+'0.01'+'_string'):add
In [72]: np.char.add(np.char.add('string_',xx),'_string')
Out[72]:
array(['string_0.1_string', 'string_0.2_string', 'string_0.3_string'],
dtype='<U19')
numpy
没有用于处理字符串的特殊代码,因此函数通常以与列表推导相同的速度运行。char
有一个 ,但它对数组的字符进行操作:char.join
In [74]: np.char.join('_',xx)
Out[74]: array(['0_._1', '0_._2', '0_._3'], dtype='<U5')
另一种方法是使用或使用效用函数,例如:np.vectorize
np.frompyfunc
In [75]: def foo(i):
...: return '_'.join(['string',str(i),'string'])
...:
In [76]: np.frompyfunc(foo,1,1)(x)
Out[76]:
array(['string_0.1_string', 'string_0.2_string', 'string_0.3_string'],
dtype=object)
对于小数组,往往比列表推导式慢一些,但对于大型数组,它们的扩展性更好。np.vectorize/frompyfunc
但主要优点是它们可以处理多个维度和广播。
评论
0赞
Mackie Messer
11/7/2023
好。Vectorize/FromPyFunc 几乎可以肯定是要走的路。谢谢
评论
np.char
函数是 Python 字符串方法的浅层包装器。它们并不快。解释或说明您正在尝试做什么。join
join