Skip to main content
 首页 » 编程设计

python之如何在 pandas 数据框行中附加所有具有相同 id 的元素

2025年05月04日15jyk

我有下面的 pandas 数据框,我想将一系列元素转换成单个列,而不会丢失 id 和 fruit 列的时间顺序.

id   fruit 
---|------ 
101  apple 
102  apple 
101  watermelon 
101  orange 
102  orange 
104  lemon 
105  lemon 
104  lemon 
105  apple 
103  grapes 

例如,新数据框应如下所示(*):

id               col 
101  apple, watermelon, orange 
102  apple, orange 
103  grapes 
104  lemon, lemon 
105  apple 

我尝试过:

f = {'url' : lambda x: np.unique(x).tolist()} 
df = df.groupby('id', as_index=False).agg(f).reindex(columns=df.columns) 
 
 
def foo(row): 
    #just to remove the brackets 
    return ', '.join(row) 
 
df4['url'] = df4['fruit'].apply(tweak) 
df4 

但是,尽管这在我这样做时有效:

list(df.loc[[362]]['fruit']) 

每一行中收集的信息没有临时排序(按照 fruit 列的出现顺序)。因此,我怎样才能得到 (*)?

请您参考如下方法:

apply join with set

df.groupby('id').fruit.apply(lambda x : ','.join(set(x))).reset_index() 
Out[82]:  
    id                    fruit 
0  101  apple,watermelon,orange 
1  102             apple,orange 
2  103                   grapes 
3  104                    lemon 
4  105              apple,lemon