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

使用Pandas从字符串切片生成新列时返回NaN的问题求助

问题排查与解决

问题出在str[]语法不支持直接传入Series作为起止索引——它只能接受单个常量值,用Series的话会被判定为无效参数,所以返回全NaN。给你两种靠谱的解决方式:

方法1:用apply逐行处理(直观易理解)

直接按行遍历DataFrame,每一行单独取字符串和对应的起止索引做切片:

df['level1'] = df.apply(lambda row: row['currentagentsnapshot'][row['start']:row['stop']], axis=1)

方法2:用str.slice矢量化处理(效率更高)

pandas的str.slice方法原生支持传入Series作为start和stop参数,适合大数据量场景:

df['level1'] = df['currentagentsnapshot'].str.slice(start=df['start'], stop=df['stop'])

额外验证步骤

如果还是有问题,先确认start和stop列是整数类型(比如计算后可能是float格式的10.0,需转成int):

df['start'] = df['start'].astype(int)
df['stop'] = df['stop'].astype(int)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:40:53