如何创建新列来存储重复ID列的数据?

2024-04-25 06:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个数据帧:

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

我想根据需要创建额外的key列,以便在存在重复的IDs时将数据存储在key列中

这是输出的一个片段:

   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"  

有什么建议或想法我应该如何处理这个问题吗?你知道吗

谢谢你


Tags: ofthe数据keyinidnewcolumn
2条回答

可以将^{}^{}一起使用:

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

查看groupbyapply。它们各自的文档是herehere。您可以unstackdocs)创建的多索引的额外级别。你知道吗

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作为列,可以调用此数据帧上的reset_index。你知道吗

相关问题 更多 >