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

Python如何从DataFrame列的列表字符串中提取整数值?

解决DataFrame中Ticket列从单元素列表转整数的问题

方法一:使用.apply()配合lambda(推荐)

这是最简洁高效的方式,直接对Series的每个元素操作:

train_tickets["Ticket"] = train_tickets["Ticket"].apply(lambda x: int(x[0]))

执行后,train_tickets["Ticket"].head()会返回预期的整数结果:

1    211536
2    112053
3      6607
4    111369
5    370376

方法二:使用循环实现

你之前的循环出错是因为遍历train_tickets["Ticket"]时,row是列表元素(比如[211536])而非索引,用列表作为索引会触发KeyError。以下是两种正确的循环写法:

写法1:遍历索引

for idx in train_tickets.index:
    train_tickets.loc[idx, "Ticket"] = int(train_tickets["Ticket"][idx][0])

写法2:使用iterrows()

for idx, row in train_tickets.iterrows():
    train_tickets.loc[idx, "Ticket"] = int(row["Ticket"][0])

错误原因说明

你之前的循环代码:

for row in train_tickets["Ticket"]:
    Y = int(train_tickets["Ticket"][row][0])

这里的row是Series中的每个列表值(例如[211536]),而非行索引。当你用train_tickets["Ticket"][row]时,相当于用列表作为索引去取值,这不符合pandas的索引规则,因此抛出KeyError。

内容的提问来源于stack exchange,提问作者J. Rumpelstiltskin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:01:01