【问题标题】:How to Create New Columns to Store the Data of the Duplicate ID Column?如何创建新列来存储重复 ID 列的数据?
【发布时间】:2016-12-08 14:14:01
【问题描述】:

我有这个数据框:

   ID  key
0   1    A
1   1    B
2   2    C
3   3    D
4   3    E
5   3    E

当有重复的IDs 时,我想创建额外的key 列以将数据存储在key 列中

这是输出的sn-p:

   ID  key  key2  
0   1    A     B # Note: ID#1 appeared twice in the dataframe, so the key value "B"
                 # associated with the duplicate ID will be stored in the new column "key2"

完整的输出应如下所示:

    ID  key  key2   key3
0   1    A      B    NaN
1   2    C    NaN    NaN
2   3    D      E      E # The ID#3 has repeated three times.  The key of                    
                         # of the second repeat "E" will be stored under the "key2" column
                         # and the third repeat "E" will be stored in the new column "key3"  

任何建议或想法我应该如何解决这个问题?

谢谢,

【问题讨论】:

    标签: python regex pandas dataframe format


    【解决方案1】:

    查看groupbyapply。他们各自的文档是herehere。您可以unstack (docs) 创建的 MultiIndex 的额外级别。

    df.groupby('ID')['key'].apply(
        lambda s: pd.Series(s.values, index=['key_%s' % i for i in range(s.shape[0])])
    ).unstack(-1)
    

    输出

       key_0 key_1 key_2
    ID                  
    1      A     B  None
    2      C  None  None
    3      D     E     E
    

    如果您想将ID 作为一列,您可以在此DataFrame 上调用reset_index

    【讨论】:

    • 太棒了!是否可以使代码处理相同的数据帧,但使用附加列AltterKey,因此数据帧将总共有 3 列(IDkeyAlterKey)。我应该如何修改代码以使其正常工作? @亚历克斯
    • 我的意思是如何将lambda 函数应用于新列AlterKey?谢谢,@Alex
    【解决方案2】:

    您可以将cumcountpivot_table 一起使用:

    df['cols'] = 'key' + df.groupby('ID').cumcount().astype(str)
    print (df.pivot_table(index='ID', columns='cols', values='key', aggfunc=''.join))
    cols key0  key1  key2
    ID                   
    1       A     B  None
    2       C  None  None
    3       D     E     E
    

    【讨论】:

      猜你喜欢
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 2019-09-13
      • 1970-01-01
      相关资源
      最近更新 更多