【问题标题】:Python data Manipulation: Splitting Data from one column to make more rows in the same dataframePython数据操作:从一列中拆分数据以在同一数据框中创建更多行
【发布时间】:2026-02-05 05:30:01
【问题描述】:

所以我的输入是:

   Col1         Col2      Col3 Col4
0   123  abc,def,ghi  Country1  XXX
1   456      pqr,stu  Country2   XX
2   789          xyz  Country2   YY

我希望我的输出为:

   Col1      Col2    Col3   Col4
0    abc     123  Country1    XXX
1    def     123  Country1    XXX
2    ghi     123  Country1    XXX
3    pqr     456  Country2     XX
4    stu     456  Country2     XX
5    xyz     789  Country2     YY

请问最pythonic的方法是什么?谢谢vm!

【问题讨论】:

    标签: python pandas dataframe multiple-columns data-manipulation


    【解决方案1】:

    您可以使用str.splitstackjoin 创建Series 到原始DataFrame

    print (df.Col2
          .str
          .split(',',expand=True)
          .stack()
          .reset_index(drop=True, level=1)
          .rename('Col2'))
    
    0    abc
    0    def
    0    ghi
    1    pqr
    1    stu
    2    xyz
    Name: Col2, dtype: object
    
    
    print (df.drop('Col2', axis=1)
                 .join
                 (
                 df.Col2
                 .str
                 .split(',',expand=True)
                 .stack()
                 .reset_index(drop=True, level=1)
                 .rename('Col2')           
                 ))
    
       Col1      Col3 Col4 Col2
    0   123  Country1  XXX  abc
    0   123  Country1  XXX  def
    0   123  Country1  XXX  ghi
    1   456  Country2   XX  pqr
    1   456  Country2   XX  stu
    2   789  Country2   YY  xyz
    

    【讨论】:

    • aha - expand=True 在拆分 + 堆栈中!非常感谢!
    【解决方案2】:

    使用extractalljoin

    d1 = df.Col2.str.extractall('([^,]+)') \
           .rename(columns={0: 'Col2'}) \
           .reset_index(1, drop=True)
    
    df.drop('Col2', 1).join(d1).reindex_axis(df.columns, 1)
    

    【讨论】:

    • 很有趣 - 不知道 extractall .. 谢谢会尝试一下
    最近更新 更多