gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:54:31 25 4
gpt4 key购买 nike

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

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

关于python - 如何在 pandas 数据框行中附加所有具有相同 id 的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50659967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com