【问题标题】:Most efficient way to convert pandas series of integers to strings?将熊猫系列整数转换为字符串的最有效方法?
【发布时间】:2014-12-31 21:18:15
【问题描述】:

.astype(str) 是将一系列整数转换为一系列字符串的最有效方法吗?好像比较慢所以想问问。

【问题讨论】:

  • 这使用了一个 nansafe 的内部例程。但是,空值检查非常便宜,所以让它采用快速路径(如果没有空值)是有意义的。问题在这里:github.com/pydata/pandas/issues/8732

标签: python string pandas series


【解决方案1】:

我尝试了一些方法并找到了使用 numpy 的更快方法:

setup = """
import pandas, numpy
s = pandas.Series(numpy.random.randint(1,10,(100)))
"""

>>> timeit.timeit('s.astype(str)', setup=setup, number=10000)
3.33058500289917
>>> timeit.timeit('s.apply(str)', setup=setup, number=10000)
3.572000026702881
>>> timeit.timeit('s.apply(lambda x: str(x))', setup=setup, number=10000)
3.821247100830078
>>> timeit.timeit('s.values.astype(numpy.str)', setup=setup, number=10000)
0.08432412147521973

如您所见,使用 values 访问 numpy 数组并使用 astype 调用比下一个最快的方法快 40 倍以上。

【讨论】:

    猜你喜欢
    • 2018-11-01
    • 2017-07-31
    • 2023-04-07
    • 1970-01-01
    • 2021-04-17
    • 2017-03-28
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多