gpt4 book ai didi

python pandas合并序列中具有相同值的行并重新排序(删除序列中的重复项)

转载 作者:行者123 更新时间:2023-12-01 08:47:12 24 4
gpt4 key购买 nike

假设我有下表:

ID    FRUIT    ORDER
01 apple 1
01 apple 2
01 peach 3
01 apple 4
02 melon 1
02 apple 2
02 apple 3
02 apple 4

现在,当值以迭代方式相等时,我想合并同一 ID 内的行(如果它们在序列中,则删除重复项)并重新定义订单号,例如

ID    FRUIT    ORDER
01 apple 1
01 peach 2
01 apple 3
02 melon 1
02 apple 2

编辑:我忘记重新排序。如上:应该以迭代的方式重新排列顺序

最佳答案

使用boolean indexing仅过滤第一个连续值 cumcount对于新订购:

a = df['ID'] + df['FRUIT']
#if necessary
#a = df['ID'].astype(str) + df['FRUIT']
df = df[a.ne(a.shift())]
df['ORDER'] = df.groupby('ID').cumcount().add(1)
print (df)
ID FRUIT ORDER
0 01 apple 1
2 01 peach 2
3 01 apple 3
4 02 melon 1
5 02 apple 2

关于python pandas合并序列中具有相同值的行并重新排序(删除序列中的重复项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53259974/

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