This question already has an answer here:
这个问题在这里已有答案:
- Concatenate item in list to strings 4 answers
将列表中的项连接到字符串4个答案
Is it possible to vectorize the calculation of the sum of a string array in numpy?
是否有可能在numpy中对字符串数组的总和进行向量化计算?
With a loop, I would do this:
有了循环,我会这样做:
import numpy as np
myarray = np.array(['a','b','c'])
mysum = ''
for i in myarray:
mysum += i
print(mysum) #result: 'abc'
For floats, one can simply use the sum function:
对于浮点数,可以简单地使用sum函数:
myarray_float = np.array([1.0,2.0,3.0])
print(myarray_float.sum()) # result: 6.0
However, this is not possibe for arrays of strings, but leads to Type error: cannot perform reduce with flexible type.
但是,这不适用于字符串数组,但会导致类型错误:无法使用灵活类型执行reduce。
1 个解决方案
#1
1
You can just use ''.join
:
你可以使用''。join:
import numpy as np
myarray = np.array(['a','b','c'])
''.join(myarray)
# 'abc'
#1
1
You can just use ''.join
:
你可以使用''。join:
import numpy as np
myarray = np.array(['a','b','c'])
''.join(myarray)
# 'abc'