Dig*_*ant 1 python arrays lambda numpy
我有一大堆这样的数字:cols = np.arange(1, 6).我想在cols中的每个数字前面添加字母't'.我写了followind loc:
f = lambda x: 't' + str(x)
temp = f(cols)
print(temp)
Run Code Online (Sandbox Code Playgroud)
我得到这样的输出:
t[1 2 3 4 5].
Run Code Online (Sandbox Code Playgroud)
我需要输出为['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')
Run Code Online (Sandbox Code Playgroud)
它比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
Run Code Online (Sandbox Code Playgroud)