【问题标题】:How to create new rows from values inside in a cloumn of pandas dataframe based on delimeter in Python?python - 如何根据Python中的分隔符从pandas数据框列中的值创建新行?
【发布时间】:2026-01-08 11:35:02
【问题描述】:

我有如下数据框。我想将列 zip 中的值拆分为行值,如下所示。这些分隔符可以用_ ,. 分隔这些值。这在 python 中是如何实现的。

输入

df.head(5)

    Date    Item_Code   Type    Zip
    1/1/2020    A   Long    07_08_09
    12/4/2020   B   Small   AB_CD_EF_GF
    13/4/2020   A   Long    08_14
    1/5/2020    A   Long    
    21/5/2020   B   Small   09,07,16
    22/5/2020   B   Small   AB,07

预期输出

Date    Item_Code   Type    Zip
1/1/2020    A      Long    07
1/1/2020    A      Long    08
1/1/2020    A      Long    09
12/4/2020   B      Small   AB
12/4/2020   B      Small   CD
12/4/2020   B      Small   EF
12/4/2020   B      Small   GF
13/4/2020   A      Long    08
13/4/2020   A      Long    14
1/5/2020    A      Long 
21/5/2020   B      Small   09
21/5/2020   B      Small   07
21/5/2020   B      Small   16
22/5/2020   B      Small   AB
22/5/2020   B      Small   07

【问题讨论】:

    标签: python regex python-3.x pandas dataframe


    【解决方案1】:

    首先使用Series.str.split witg 正则表达式,通过DataFrame.assign 赋值,然后使用DataFrame.explode,我还在最后一步创建了默认唯一索引:

    df1 = (df.assign(Zip = df['Zip'].str.split('[_ ,\.]'))
             .explode('Zip')
             .reset_index(drop=True))
    print (df1)
             Date Item_Code   Type  Zip
    0    1/1/2020         A   Long   07
    1    1/1/2020         A   Long   08
    2    1/1/2020         A   Long   09
    3   12/4/2020         B  Small   AB
    4   12/4/2020         B  Small   CD
    5   12/4/2020         B  Small   EF
    6   12/4/2020         B  Small   GF
    7   13/4/2020         A   Long   08
    8   13/4/2020         A   Long   14
    9    1/5/2020         A   Long  NaN
    10  21/5/2020         B  Small   09
    11  21/5/2020         B  Small   07
    12  21/5/2020         B  Small   16
    13  22/5/2020         B  Small   AB
    14  22/5/2020         B  Small   07
    

    【讨论】:

    • 我知道你会第一个回答!每天学习新东西,谢谢。
    • @jezrael,收到错误DataFrame' object has no attribute 'explode'
    • @pankaj - 可以升级熊猫吗?
    • @jezrael,让我试试,哪个版本
    • @pankaj - 它从 0.25+ 开始工作,所以如果使用最后一个 1.0.3 它工作得很好