【问题标题】:split several columns using pandas使用熊猫拆分几列
【发布时间】:2016-05-04 16:32:25
【问题描述】:

我想将字符串拆分为几列。例如,我想从下面数据框中的 col2、col3 和 col5 中选择一些信息(但实际上我有一百多列要这样做)。

d = pd.DataFrame({
                  'col1' : ['USA', 'AGN'],
                  'col2' : ['0|0:0.014:0.986,0.013,0', '1|0:0.02:1.936,0.023,1'],
                  'col3' : ['1|0:0.024:0.9,0.01345,2', '0|2:0.213:0.92,0.1,2'],
                  'col4' : ['done', 'done'],
                  'col5' : ['2|0:0.02:1.936,0.023,1', '1|0:0.024:0.9,0.01345,2']
                  })

  col1                     col2                     col3  col4 .....
0  USA  0|0:0.014:0.986,0.013,0  1|0:0.024:0.9,0.01345,2  done .....  
1  AGN   1|0:0.02:1.936,0.023,1     0|2:0.213:0.92,0.1,2  done .....  

我只需要那个长字符串中的前 3 个标记。然后我希望我可以从我的结果中看到,如下所示。

col1 col2  col3  col4  col5  ....
USA   0|0   1|0  done   2|0  ....
AGN   1|0   0|2  done   1|0  ....

有什么提示吗?

【问题讨论】:

    标签: python python-2.7 pandas dataframe


    【解决方案1】:

    如果我正确理解了你的问题,你可以这样做:

    In [254]: d.replace(r':.*', '', regex=True)
    Out[254]:
      col1 col2 col3  col4 col5
    0  USA  0|0  1|0  done  2|0
    1  AGN  1|0  0|2  done  1|0
    

    【讨论】:

      【解决方案2】:

      获取前三个字符串字符:

      >>> d.col2.str[:3]
      0    0|0
      1    1|0
      Name: col2, dtype: object
      

      在“:”上拆分并取第一项:

      >>> d.col2.str.split(':', expand=True)[0]
      0    0|0
      1    1|0
      Name: 0, dtype: object
      

      将其应用于一组列:

      cols = ['col2', 'col3', 'col5']
      d.loc[:, cols] = d.loc[:, cols].apply(lambda s: s.str[:3])
      
      >>> d
        col1 col2 col3  col4 col5
      0  USA  0|0  1|0  done  2|0
      1  AGN  1|0  0|2  done  1|0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-28
        • 1970-01-01
        • 2016-08-30
        • 2019-04-11
        • 1970-01-01
        相关资源
        最近更新 更多