【问题标题】:split pandas column to many columns将 pandas 列拆分为多列
【发布时间】:2021-01-24 10:00:48
【问题描述】:

我有如下数据框:

     ColumnA      ColumnB         ColumnC
0       usr       usr1,usr2       X1
1       xyz       xyz1,xyz2,xyz3  X2
2       abc       abc1,abc2,abc3  X3

我想做的是:

  • 用“,”分割B列

  • 问题是B列的一些单元格有3个变量(xyz1,xyz2,xyz3),其中一些是6个等。它不稳定。

预期输出:

     ColumnA      ColumnB          usercol1    usercol2    usercol3  ColumnC
0       usr       usr1,usr2           usr1      usr2           -       X1
1       xyz       xyz1,xyz2,xyz3      xyz1      xyz2          xyz3     X2
2       abc       abc1,abc2,abc3      abc1      abc2          abc3     X3

【问题讨论】:

  • 请发布您的预期输出
  • 感谢您的关注,我添加了预期的输出。

标签: pandas dataframe split


【解决方案1】:
  1. 创建一个使用expand=Truestr.split() 的新数据框
  2. 然后concat 前两列,新的扩展数据框和第三个原始数据框列。这是动态到不均匀的列表长度。

df1 = df['ColumnB'].str.split(',',expand=True).add_prefix('usercol')
df1 = pd.concat([df[['ColumnA', 'ColumnB']],df1, df[['ColumnC']]], axis=1).replace(np.nan, '-')
df1
Out[1]: 
     ColumnA      ColumnB          usercol0    usercol1    usercol2  ColumnC
0       usr       usr1,usr2           usr1      usr2          -        X1
1       xyz       xyz1,xyz2,xyz3      xyz1      xyz2          xyz3     X2
2       abc       abc1,abc2,abc3      abc1      abc2          abc3     X3

从技术上讲,这也可以用一行来完成:

df = pd.concat([df[['ColumnA', 'ColumnB']],
                df['ColumnB'].str.split(',',expand=True).add_prefix('usercol'),
                df[['ColumnC']]], axis=1).replace(np.nan, '-')
df
Out[1]: 
  ColumnA         ColumnB usercol0 usercol1 usercol2 ColumnC
0     usr       usr1,usr2     usr1     usr2        -      X1
1     xyz  xyz1,xyz2,xyz3     xyz1     xyz2     xyz3      X2
2     abc  abc1,abc2,abc3     abc1     abc2     abc3      X3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 2018-02-25
    • 2016-05-31
    • 2020-02-10
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多