int('0'+s)
Prepend the string with a zero. Think of it as a miniature parsing step.
I can't think of a case when this wouldn't work.
This is the use-case I had:
Convert a numpy array of strings to integers.
def _intStrArray(pos): return int('0'+pos)
np.intStrArray = np.vectorize(_intStrArray)
print(arr)
array([['', '', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '1', '', '', '2', '', '2', '', '', '', '', ''],
['', '2', '2', '', '3', '2', '', '', '2', '', '', '', ''],
['', '2', '', '3', '2', '2', '3', '4', '', '4', '', '', ''],
['', '', '3', '2', '2', '', '', '3', '3', '', '2', '1', ''],
['', '', '', '1', '2', '', '3', '2', '', '', '', '', ''],
['', '', '2', '', '2', '4', '3', '', '2', '1', '', '2', ''],
['', '', '', '', '', '', '2', '', '', '1', '', '1', ''],
['', '', '', '', '', '', '', '', '', '', '', '', '']], dtype=object)
print(np.intStrArray(arr))
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0],
[0, 2, 2, 0, 3, 2, 0, 0, 2, 0, 0, 0, 0],
[0, 2, 0, 3, 2, 2, 3, 4, 0, 4, 0, 0, 0],
[0, 0, 3, 2, 2, 0, 0, 3, 3, 0, 2, 1, 0],
[0, 0, 0, 1, 2, 0, 3, 2, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 2, 4, 3, 0, 2, 1, 0, 2, 0],
[0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
After discovering just how messy my data was, I also added a str(). This is optional if the datatype is reliable.
def _intStrArray(pos): return int('0'+str(pos))
np.intStrArray = np.vectorize(_intStrArray)