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

pandas使用explode方法时如何禁止指定列(如description)被展开

解决方案

你可以直接使用pandas内置的DataFrame.explode()方法,显式指定需要展开的列,其余列会自动保留原始值不会被展开,代码实现更简洁可控:

import pandas as pd

# 原有拆分price、weight列的逻辑保持不变
data['price'] = data['price'].str.split(',')
data['weight'] = data['weight'].str.split(',')

# 仅对指定的price、weight列执行展开操作,其余列自动保留原值
data = data.explode(['price', 'weight'], ignore_index=True)

原代码问题说明

你之前采用set_index+apply explode的写法,如果你把description从索引参数中移除,它会作为普通列被纳入apply(pd.Series.explode)的处理范围:如果该列是可迭代的列表结构就会被展开,就算不是列表结构,这种写法也存在误操作其他列的风险,直接使用指定列的explode是更符合需求的实现方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:57:01