我有一个像这样的数字数组:cols = np.arange(1, 6)。我想在 cols 中的每个数字前附加字母“t”。我写了 followind loc:
f = lambda x: 't' + str(x)
temp = f(cols)
print(temp)
我得到这样的输出:
t[1 2 3 4 5].
我需要输出为 ['t1', 't2', 't3'...]。我需要为 1000 个数字做这件事。我做错了什么?
请您参考如下方法:
您可以使用np.core.char.add:
np.core.char.add('t', np.arange(1,6).astype(str))
#array(['t1', 't2', 't3', 't4', 't5'],
# dtype='|S12')
对于大型数组,它比 list(map(...)) 更快:
%timeit np.core.char.add('t', np.arange(1,100000).astype(str))
# 10 loops, best of 3: 31.7 ms per loop
f = lambda x: 't' + str(x)
%timeit list(map(f, np.arange(1,100000).astype(str)))
# 10 loops, best of 3: 38.8 ms per loop
