如何提取DataFrame列表列的最长字符串及全表最长值
解决方案
你现有代码的核心问题有两个:一是range(0:2)存在语法错误,Python的range参数用逗号分隔,就算写成range(0,2)也仅遍历前2行,无法覆盖全量数据;二是手动for循环遍历不符合pandas的最佳实践,代码冗余还容易出索引错误。
可以直接用pandas的apply方法实现需求,完整实现代码如下:
import pandas as pd # 构造样例DataFrame,实际使用时替换为你自己的数据源即可 df = pd.DataFrame({ 'items': [ ['pants','hat'], ['clothes'], ['mouse','xx'] ] }) # 生成longest_str列,按你要求用列表包裹最长字符串 df['longest_str'] = df['items'].apply(lambda x: [max(x, key=len)]) # 计算整个DataFrame中的最长字符串 global_longest = max(df['longest_str'].str[0], key=len) # 输出验证 print(df) print("全局最长字符串:", global_longest)
运行输出结果
items longest_str 0 [pants, hat] [pants] 1 [clothes] [clothes] 2 [mouse, xx] [mouse] 全局最长字符串: clothes
注意事项
- 如果你不需要
longest_str列的值是列表格式,仅需要存字符串本身,把lambda里的外层方括号去掉即可:lambda x: max(x, key=len) - 该方案无需手动写循环,自动适配任意行数的DataFrame,性能远高于手动遍历实现
内容的提问来源于stack exchange,提问作者Joe Ng
相关产品推荐
相关产品推荐

