Find length of longest string in Pandas dataframe column

前端 未结 5 662
忘掉有多难
忘掉有多难 2020-12-23 13:18

Is there a faster way to find the length of the longest string in a Pandas DataFrame than what\'s shown in the example below?

import numpy as np
import panda         


        
5条回答
  •  甜味超标
    2020-12-23 14:06

    DSM's suggestion seems to be about the best you're going to get without doing some manual microoptimization:

    %timeit -n 100 df.col1.str.len().max()
    100 loops, best of 3: 11.7 ms per loop
    
    %timeit -n 100 df.col1.map(lambda x: len(x)).max()
    100 loops, best of 3: 16.4 ms per loop
    
    %timeit -n 100 df.col1.map(len).max()
    100 loops, best of 3: 10.1 ms per loop
    

    Note that explicitly using the str.len() method doesn't seem to be much of an improvement. If you're not familiar with IPython, which is where that very convenient %timeit syntax comes from, I'd definitely suggest giving it a shot for quick testing of things like this.

    Update Added screenshot:

提交回复
热议问题