【Pandas】Pandas求某列字符串的长度,总结经验教训

版权声明:本文为博主原创文章,转载请在文章开头注明出处,作者:ChenVast;原文链接: https://blog.csdn.net/ChenVast/article/details/82758281

测试集大小:

test.shape

(898, 11) 

对某列的字符串做统计长度

1、for遍历法:

start = time.time()
for i in test.index.values:
    test.loc[i,'contentLen1'] = len(test.loc[i,'content'])
time.time() - start

 47.16238021850586

2、使用pandas的内置方法.str

%time test['contentLen2'] = test['content'].str.len()

Wall time: 61 ms 
 

结论

上面例子可以得出,使用pandas时千万不要盲目的使用for遍历,要学会使用pandas提供的内置方法。

for和.str方法之间的性能差距过大,不在一个数量级。使用for会造成频繁的赋值操作,造成不必要内存消耗和计算时长。

以上测试用例才898行,for的赋值耗时高达47秒,生产上的都是几百万行的数据,使用for那不就直接凉凉了?

且行且珍惜啊!

猜你喜欢

转载自blog.csdn.net/ChenVast/article/details/82758281
今日推荐