python - 从 groupby 2 列之后的第 3 列获取相应的值

标签 python pandas group-by

以下代码对每个类别的“时间”最大值进行分组。
我想获得“目标”变量中的相应值,但我不知道如何去做。
任何提示?

import numpy as np
import pandas as pd

data=[[1,1,2,2,'A'],
      [2,5,5,1,'A'],
      [3,7,9,4,'B'],
      [1,5,1,9,'B'],
      [1,8,2,8,'C'],
      [2,8,5,10,'C'],
      [0,1,2,3,'D']]

df=pd.DataFrame(data, columns=['time','x','y','target','categ'])
res = ((df.groupby('categ')['time'].max().value_counts(ascending=True).sort_index()))
print(res)

最佳答案

我们可以使用 loc + groupby idxmax :

res = df.loc[
    df.groupby('categ')['time'].idxmax(),
    ['time', 'target']
].sort_values('time')['target']
res :
6     3
1     1
5    10
2     4
Name: target, dtype: int64

或者用 groupby transform 过滤max 如果需要匹配组最大值的所有行:
res = df.loc[
    df.groupby('categ')['time'].transform('max').eq(df['time']),
    ['time', 'target']
].sort_values('time')['target']
res :
6     3
1     1
5    10
2     4
Name: target, dtype: int64
*在这种情况下,输出是相同的,但如果每个 categ 有重复的最大值,则输出不会相同。 .

根据 groupby agg 的评论在 time并汇总到列表中:
res = df.groupby('time')['target'].agg(list)
res :
time
0          [3]
1    [2, 9, 8]
2      [1, 10]
3          [4]
Name: target, dtype: object

关于python - 从 groupby 2 列之后的第 3 列获取相应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68505255/

相关文章:

python - 网状结构的配置/安装问题 [R]

Python 安装 'asyncio' 错误 : cl. exe 失败,退出状态 2

C# 对象按组排序,使用 linq

MySQL:按最大日期分组和排序

python - 如何避免在 Python 中两次查找字典以获取/设置键值?

python - 忽略工具提示文本并仅获取当前使用 Beautiful Soup 显示的文本

python - matplotlib 中的图例设置(numpoints 和 scatterpoints)不起作用

python - 如何合并两个pandas数据框?

python - Pandas 数据帧转换 : adding columns from dictionary k-v pairs

python - 在给定索引列表的情况下将多行插入数据帧的最快方法(python)