值得一开始,因为任何调查,与流行的观点之前看实际表现,list(map(str, x))
似乎是 慢 比x.apply(str)
。
import pandas as pd, numpy as np
### Versions: Pandas 0.20.3, Numpy 1.13.1, Python 3.6.2 ###
x = pd.Series(np.random.randint(0, 100, 100000))
%timeit x.apply(str) # 42ms (1)
%timeit x.map(str) # 42ms (2)
%timeit x.astype(str) # 559ms (3)
%timeit [str(i) for i in x] # 566ms (4)
%timeit list(map(str, x)) # 536ms (5)
%timeit x.values.astype(str) # 25ms (6)
值得注意的一点:
这 似乎是 因为它使用了快速编译的Cython代码:
cpdef ndarray[object] astype_str(ndarray arr):
cdef:
Py_ssize_t i, n = arr.size
ndarray[object] result = np.empty(n, dtype=object)
for i in range(n):
# we can use the unsafe version because we kNow `result` is mutable
# since it was created from `np.empty`
util.set_value_at_unsafe(result, i, str(arr[i]))
return result
熊猫适用str
于该系列中的每个项目,而不使用上述Cython。
因此,性能可与[str(i) for i in x]
/相媲美list(map(str, x))
。
Numpy不会在数组的每个元素上应用函数。我发现了对此的一种描述:
如果您做s.values.astype(str)
了,您将得到一个持有的对象int
。这是numpy
在进行转换,而熊猫会遍历每个项目并调用str(item)
它。因此,如果您s.astype(str)
拥有对象持有权str
。
有一个技术原因,在没有空值的情况下,尚未实现numpy版本。