【问题标题】:How can we split the contents of a whole column into separate columns within the same table?我们如何将整列的内容拆分为同一个表中的单独列?
【发布时间】:2018-02-28 14:00:15
【问题描述】:

假设我用pandas读取datatable.csv,表格是这样的:

我们如何拆分第 3 列,使数据表随后看起来像这样:

我已经阅读了大量类似问题的答案,并尝试使用 .str.rpartition('-').split('-').apply() 组合之类的方法,但我没有设法将分离的值提取到列中。

【问题讨论】:

    标签: python pandas split dataset


    【解决方案1】:

    splitexpand=True 一起使用:

    df[['Column 3','Column 4','Column 5']] = df['Column 3'].str.split('-', expand=True)
    

    例子

    df = pd.DataFrame({'Column 3':['X-X-0','1-0-X','X-Y-X','X-0-0','1-X-Y']})
    df[['Column 3','Column 4','Column 5']] = df['Column 3'].str.split('-', expand=True)
    

    输出:

      Column 3 Column 4 Column 5
    0        X        X        0
    1        1        0        X
    2        X        Y        X
    3        X        0        0
    4        1        X        Y
    

    【讨论】:

      【解决方案2】:

      你可以用这个

      df['col3']= ['1-d-w','s-3-q']
      
      df
      Out[4]: 
           col
      0  1-d-w
      1  s-3-q
      df['col4']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[0]))
      df['col5']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[1]))
      df['col6']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[2]))
      df
      Out[33]: 
          col3  col4  col5  col6
      0  1-d-w     1     d     w
      1  s-3-q     s     3     q
      

      【讨论】:

        猜你喜欢
        • 2015-04-03
        • 1970-01-01
        • 2018-05-17
        • 2022-11-23
        • 2014-11-17
        • 1970-01-01
        • 2017-11-02
        • 2021-10-12
        • 1970-01-01
        相关资源
        最近更新 更多