【发布时间】:2021-01-03 23:03:17
【问题描述】:
import pandas as pd
df = {'a': ['xxx', 'xxx','xxx','yyy','yyy','yyy'], 'start': [10000, 10500, 11000, 12000, 13000, 14000] }
df = pd.DataFrame(data=df)
df_new = df.groupby("a",as_index=True).agg(
ProcessiveGroupLength=pd.NamedAgg(column='start', aggfunc="count"),
StartMin=pd.NamedAgg(column='start', aggfunc="min"),
StartMax=pd.NamedAgg(column='start', aggfunc="max"),
)
给予
>>>df_new
ProcessiveGroupLength StartMin StartMax
a
xxx 3 10000 11000
yyy 3 12000 14000
如何在飞行中到达下方,因为我认为飞行中会更快。
>>>df_new
ProcessiveGroupLength Diff
a
xxx 3 1000
yyy 3 2000
以下代码给出以下错误消息:
Traceback(最近一次通话最后一次): 文件“”,第 5 行,在 TypeError: 不支持的操作数类型 -: 'str' 和 'str'
df_new = df.groupby("a").agg(
ProcessiveGroupLength=pd.NamedAgg(column='start', aggfunc="count"),
Diff=pd.NamedAgg(column='start', aggfunc="max"-"min"),)
【问题讨论】:
-
您实际上会感到惊讶,但之后执行减法可能是您最高效的结果。这是因为通过添加另一个聚合器,您要求 pandas 为每个组找到两次最小值和最大值。一次用于 StartMin,一次用于 StartMax,然后在计算 Diff 时再进行 2 次。
-
@CameronRiddell 谢谢,。事实上,我想以最快速、最有效的方式找到差异。因此我删除了不必要的列。
标签: pandas dataframe pandas-groupby aggregate-functions