如何拆分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
相关产品推荐
相关产品推荐

