python - 在 Pandas 的一个聚合中使用多个 idxmin() 和 idmax() 进行多重索引

标签 python r python-3.x pandas data.table

在 R data.table 中,使用 argmin 或 argmax 函数在一个聚合中聚合多个列是可能且容易的。例如对于 DT:

> DT = data.table(id=c(1,1,1,2,2,2,2,3,3,3), col1=c(1,3,5,2,5,3,6,3,67,7), col2=c(4,6,8,3,65,3,5,4,4,7), col3=c(34,64,53,5,6,2,4,6,4,67))
> DT
    id col1 col2 col3
 1:  1    1    4   34
 2:  1    3    6   64
 3:  1    5    8   53
 4:  2    2    3    5
 5:  2    5   65    6
 6:  2    3    3    2
 7:  2    6    5    4
 8:  3    3    4    6
 9:  3   67    4    4
10:  3    7    7   67

> DT_agg = DT[, .(agg1 = col1[which.max(col2)]
                , agg2 = col2[which.min(col3)]
                , agg3 = col1[which.max(col3)])
              , by= id]
> DT_agg
   id agg1 agg2 agg3
1:  1    5    4    3
2:  2    5    3    5
3:  3    7    4    7

agg1 是 col1 的值,其中 col2 的值是最大值,按 id 分组。

agg2 是 col2 的值,其中 col3 的值是最小值,按 id 分组。

agg3 是 col1 的值,其中 col3 的值是最大值,按 id 分组。

这在 Pandas 中怎么可能,使用 groupby 和 agg 在一个聚合操作中完成所有三个聚合?我不知道如何在 Python 的一个 agg 函数中合并三种不同的索引。这是 Python 中的数据框:
DF =pd.DataFrame({'id':[1,1,1,2,2,2,2,3,3,3], 'col1':[1,3,5,2,5,3,6,3,67,7], 'col2':[4,6,8,3,65,3,5,4,4,7], 'col3':[34,64,53,5,6,2,4,6,4,67]})

DF
Out[70]: 
   id  col1  col2  col3
0   1     1     4    34
1   1     3     6    64
2   1     5     8    53
3   2     2     3     5
4   2     5    65     6
5   2     3     3     2
6   2     6     5     4
7   3     3     4     6
8   3    67     4     4
9   3     7     7    67

最佳答案

你可以试试这个

DF.groupby('id').agg(agg1=('col1',lambda x:x[DF.loc[x.index,'col2'].idxmax()]),
                     agg2 = ('col2',lambda x:x[DF.loc[x.index,'col3'].idxmin()]),
                     agg3 = ('col1',lambda x:x[DF.loc[x.index,'col3'].idxmax()]))

    agg1  agg2  agg3
id
1      5     4     3
2      5     3     5
3      7     4     7

关于python - 在 Pandas 的一个聚合中使用多个 idxmin() 和 idmax() 进行多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62295617/

相关文章:

Python最佳实践: How to handle function parameters that can be 2 types?

r - 同时对数据框的特定列进行子集化和操作

r - 使用 data.table 编写具有聚合功能的 R 函数

python-3.x - spacy中的nlp是什么?

python - 错误 "unsupported operand type(s) for -: ' str' 和 'float' ?

python - imap - 如何删除消息

python - 从 EC2 实例本地访问 Amazon S3 Bucket

python - 用 Pandas 数据框中另一列的值填充多列中的 Na

r - 向图例添加额外的项目

python-3.x - 填充 NxM 矩阵使得 A[i,j]=A[i-1,j] NAND A[i,j-1]