您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将一系列int转换为字符串-为什么应用比astype快得多?

将一系列int转换为字符串-为什么应用比astype快得多?

值得一开始,因为任何调查,与流行的观点之前看实际表现,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版本

其他 2022/1/1 18:42:51 有412人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶