gpt4 book ai didi

python - 如何在不排序的情况下迭代组?

转载 作者:行者123 更新时间:2023-11-30 22:23:34 25 4
gpt4 key购买 nike

我有一个像这样仔细排序的数据框:

x = pd.DataFrame({'col1':['b', 'e','e', 'g','g', 'f','f'],
'col2':['f', 'g','f', 'f','e', 'g','e'],
'col3':[ 1 , 7 , 2 , 6 , 7 , 20, 5 ]})

我想将各组汇总为每行一行,保留顺序

names, totals, fs = zip(* list( (name, total(group), f(group)) for name, group in x.groupby('col1'))  )

out = pd.DataFrame({'lang':names,
'total':totals,
'partners':tails})

但是在 out行按 col1 排序。而x.groupby('col1').heads()以正确的顺序生成所有内容,如 [name for name, _ in x.groupby('col1')] 所示进行迭代返回['b', 'e', 'f', 'g']何时“f”应位于“g”后面

如何在不排序的情况下循环遍历组?

最佳答案

正如评论中所讨论的,您所需要的只是

groupby("col1", sort=False)

取自 the documentation :

sort : boolean, default True

Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group.

关于python - 如何在不排序的情况下迭代组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029070/

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