Find length of longest string in Pandas dataframe column

前端 未结 5 671
忘掉有多难
忘掉有多难 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 13:59

    Sometimes you want the length of the longest string in bytes. This is relevant for strings that use fancy Unicode characters, in which case the length in bytes is greater than the regular length. This can be very relevant in specific situations, e.g. for database writes.

    df_col_len = int(df[df_col_name].str.encode(encoding='utf-8').str.len().max())
    

    The above line has the extra str.encode(encoding='utf-8'). The output is enclosed in int() because it is otherwise a numpy object.

提交回复
热议问题