2

Is it possible to vectorize the calculation of the sum of a string array in 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:

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.

Niklas M.
  • 91
  • 1
  • 7
  • 2
    I don't know numpy. I just want to comment that what you call "sum of a string" is technically called "string concatenation". Perhaps this terminology will help you with further google searches. – Code-Apprentice Mar 26 '18 at 15:58

1 Answers1

2

You can just use ''.join:

import numpy as np

myarray = np.array(['a','b','c'])

''.join(myarray)

# 'abc'
jpp
  • 159,742
  • 34
  • 281
  • 339