如何基于Pandas DataFrame列中的列表值拆分并复制行?
解决方法
首先构造示例DataFrame:
import pandas as pd df = pd.DataFrame({ 'pid': [1, 2], 'types': [['A', 'B'], ['A', 'B', 'C']], 'other_columns': ['xxxx', 'yyy'] })
步骤1:拆分列表元素为单独行
用explode方法将types列的列表元素拆分为单独行,此时types列的每个值是单个元素(如'A'、'B'):
df_exploded = df.explode('types')
步骤2:将单个元素重新包装为列表
通过apply把单个元素转为包含该元素的列表,匹配目标格式:
df_exploded['types'] = df_exploded['types'].apply(lambda x: [x])
最终得到的df_exploded就是你需要的结果:
| pid | types | other_columns |
|---|---|---|
| 1 | [A] | xxxx |
| 1 | [B] | xxxx |
| 2 | [A] | yyy |
| 2 | [B] | yyy |
| 2 | [C] | yyy |
内容的提问来源于stack exchange,提问作者Glasnhost
相关产品推荐
相关产品推荐

