代码之家  ›  专栏  ›  技术社区  ›  Anakin Skywalker

基于数据库中另一列中的重复ID将行转换为宽列

  •  0
  • Anakin Skywalker  · 技术社区  · 4 年前

    this this this 问题。

    我有一个重复ID的数据帧

    ID  Publication_type
    1   Journal          
    1   Clinical study   
    1   Guideline        
    2   Journal          
    2   Letter           
    

    publication_type 不能超过每个id的类型数。

    预期产量

     ID Publication_type1 Publication_type2 Publication_type 3    etc
     1  Journal           Clinical Study    Guideline
     2  Journal           Letter            NaN
    

    目前,我不需要将相同的发布类型放在同一列中。我不需要所有的文章在同一列。谢谢

    1 回复  |  直到 4 年前
        1
  •  1
  •   richardec    4 年前

    你可以分组 ID ,聚合通过 list ,然后根据结果创建新的数据帧:

    col = 'Publication_type'
    new_df = pd.DataFrame(df.groupby('ID')[col].agg(lambda x: x.tolist()).tolist()).replace({None: np.nan})
    new_df.columns = [f'{col}{i}' for i in new_df.columns + 1]
    new_df['ID'] = df['ID'].drop_duplicates().reset_index(drop=True)
    

    输出:

    >>> df
      Publication_type1 Publication_type2 Publication_type3  ID
    0           Journal    Clinical-study         Guideline   1
    1           Journal            Letter               NaN   2
    
    推荐文章