【问题标题】:Converting rows to wide columns based on duplicated ids in another column in pandas根据熊猫中另一列中的重复ID将行转换为宽列
【发布时间】:2022-01-23 22:18:09
【问题描述】:

我的问题类似于thisthisthis 问题。

但还是解决不了。

我有一个带有重复 ID 的数据框

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

我想让它变宽,但我不知道我将拥有多少种出版物类型 - 可能是 2 种,也可能是 20 种。因此,我不知道我需要多少列宽。 publication_type 的最大宽列大小不得超过每个 id 的类型数。

预期输出

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

现在我不需要将相同的发布类型放入同一列。我不需要同一列中的所有文章。谢谢!

【问题讨论】:

    标签: python pandas pivot melt


    【解决方案1】:

    您可以按ID 分组,通过list 聚合,然后根据结果创建一个新的DataFrame:

    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
    

    【讨论】:

    • 谢谢,但id 列消失了:)。最后一行有一个小错字 - df,而不是 d。如何保存id?谢谢!
    • 现在检查@Anakin - 我添加了另一行应该适合你;)
    猜你喜欢
    • 2019-05-22
    • 2021-03-03
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2014-11-15
    • 2020-10-04
    相关资源
    最近更新 更多