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

如何拆分DataFrame中feature列的分隔值并在下方行单独呈现

拆分DataFrame中以/分隔的特征列并多行展示

问题场景

现有如下结构的DataFrame(注意model列存在一处拼写笔误anmimal):

import pandas as pd

df = pd.DataFrame({'model':['animal','anmimal','plants','plants'],
       'kind':['cat','dog','mushroom','gingseng'],
       'feature':['cute/small','reliable/kind/big','delicious/dark','healthy/bitter/expensive']})

其中feature列的多个特征值以/分隔,需要将这些特征拆分后,每个特征单独占一行,同时保留对应行的model和kind值。

解决方案

使用pandas的str.split()拆分特征列为列表,再通过explode()将列表展开为独立行:

# 将feature列按/拆分为列表
df['feature'] = df['feature'].str.split('/')
# 展开列表为多行,重置索引
result_df = df.explode('feature', ignore_index=True)

最终结果

处理后的DataFrame如下:

model      kind    feature
0  animal       cat       cute
1  animal       cat      small
2  anmimal       dog    reliable
3  anmimal       dog       kind
4  anmimal       dog        big
5  plants  mushroom  delicious
6  plants  mushroom       dark
7  plants  gingseng    healthy
8  plants  gingseng     bitter
9  plants  gingseng  expensive

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:13:27