![](/img/trans.png)
[英]Apply different functions to different columns with a singe pandas groupby command
[英]Pandas: apply different custom functions to different columns when using groupby
我希望能够在我的 pandas dataframe 上使用“groupby”,为每一列使用不同的自定义函数。 例如,如果我将其作为输入:
annotator event interval_presence duration
3 birds [0,5] 5
3 birds [7,9] 10
3 voices [1,2] 10
3 traffic [1,7] 7
5 voices [4,7] 4
5 voices [5,10] 6
5 traffic [0,1] 4
其中“interval_presence”中的每个项目都是 pandas 间隔。 合并时,我想取“持续时间”列的平均值,我想在“interval_presence”中的间隔上使用“pd.arrays.IntervalArray”和“piso.union”。 所以这将是 output:
annotator event interval_presence duration
3 birds [[0,5],[7,9]] 7.5
3 voices [1,2] 10
3 traffic [1,7] 7
5 voices [4,10] 5
5 traffic [0,1] 4
现在,由于帖子中的答案,我知道如何合并我的间隔: Pandas:如何通过间隔并集合并行。 所以解决方案是:
data = data.groupby(['annotator', 'event'])['interval_presence'] \
.apply(pd.arrays.IntervalArray) \
.apply(piso.union) \
.reset_index()
但是我怎样才能同时将“平均”function 应用于“持续时间”?
您使用了错误的agg
语法。 尝试这个:
df.groupby(["annotator", "event"]).agg({
"interval_presence": lambda s: piso.union(pd.arrays.IntervalArray(s)),
"duration": "mean"
})
在 lambda 中, s
是一系列pd.Interval
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.