【发布时间】:2014-01-22 22:26:49
【问题描述】:
有没有比下面示例中显示的更快的方法来查找 Pandas DataFrame 中最长字符串的长度?
import numpy as np
import pandas as pd
x = ['ab', 'bcd', 'dfe', 'efghik']
x = np.repeat(x, 1e7)
df = pd.DataFrame(x, columns=['col1'])
print df.col1.map(lambda x: len(x)).max()
# result --> 6
使用 IPython 的 %timeit 计时时,运行 df.col1.map(lambda x: len(x)).max() 大约需要 10 秒。
【问题讨论】:
-
您可以通过简单地使用
map(len)来节省一些时间——lambda在这里只会浪费时间。我猜大概是 25% 左右。