You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用Pandas或聚合函数为DataFrame新增存储字符串长度的列?

不用Pandas内置函数给DataFrame新增字符串长度列的方法

如果你不想用Pandas的apply、agg这类聚合/内置函数,完全可以用你已经掌握的列表循环逻辑来处理,步骤如下:

  1. 将Pandas DataFrame转换为列表字典格式
  2. 用你写好的循环给每个字典新增字符串长度列
  3. 再把处理后的列表字典转回DataFrame

示例代码

import pandas as pd

# 初始DataFrame
df = pd.DataFrame({'x': ['abc', 'defgh', 'ijklmnop', 'qrs']})

# 转成列表字典
data = df.to_dict('records')

# 你的原有循环逻辑,新增长度列
for item in data:
    item['num_caracteres'] = len(item['x'])

# 转回DataFrame
new_df = pd.DataFrame(data)
print(new_df)

运行后会得到包含新增列的DataFrame,整个过程除了DataFrame和列表字典的转换,核心逻辑完全是你熟悉的循环操作,没有用到任何Pandas聚合函数。

内容的提问来源于stack exchange,提问作者Sunny Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 22:22:39