python - 在多索引数据框中查找列的最大值并返回其所有值

标签 python python-3.x pandas multi-index

数据集的可重现代码:

df = {'player' : ['a','a','a','a','a','a','a','a','a','b','b','b','b','b','b','b','b','b','c','c','c','c','c','c','c','c','c'],
      'week' : ['1','1','1','2','2','2','3','3','3','1','1','1','2','2','2','3','3','3','1','1','1','2','2','2','3','3','3'],
      'category': ['RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH'],
      'energy' : [75,54,87,65,24,82,65,42,35,25,45,87,98,54,82,75,54,87,65,24,82,65,42,35,25,45,98] }

df = pd.DataFrame(data= df)
df = df[['player', 'week', 'category','energy']]

Actual Dataset

我需要找到“对于每个球员,找到他能量最大的那一周,并显示该周的所有类别、能量值”

所以我所做的是:

1.设置玩家和星期为索引

2.迭代索引找到能量的最大值并返回它 值

df = df.set_index(['player', 'week'])

for index, row in df1.iterrows():
    group = df1.ix[df1['energy'].idxmax()]

获得的输出:

                category energy
  player   week     
    b        2    RES      98
             2    VIT      54
             2   MATCH     82

此获得的输出是整个数据集中的最大能量,我希望每个玩家在该周的所有其他类别及其能量中的最大值。

预期输出:

Expected Output

我试过按照评论中的建议使用 groupby 方法,

df.groupby(['player','week'])['energy'].max().groupby(level=['player','week'])

得到的输出是:

                energy  category
 player week        
   a     1        87    VIT
         2        82    VIT
         3        65    VIT
   b     1        87    VIT
         2        98    VIT
         3        87    VIT
   c     1        82    VIT
         2        65    VIT
         3        98    VIT

最佳答案

找到每个玩家的最大能量周,然后为该玩家选择该周并将所有玩家的结果连接起来。

max_energy_idx = df.groupby('player')['energy'].idxmax()  # 2, 12, 26
max_energy_weeks = df['week'].iloc[max_energy_idx]  # '1', '2', '3'
players = sorted(df['player'].unique())  # 'a', 'b', 'c'

result = pd.concat(
    [df.loc[(df['player'] == player) & (df['week'] == max_enery_week), :] 
     for player, max_enery_week in zip(players, max_energy_weeks)]
)
>>> result
   player week category  energy
0       a    1      RES      75
1       a    1      VIT      54
2       a    1    MATCH      87
12      b    2      RES      98
13      b    2      VIT      54
14      b    2    MATCH      82
24      c    3      RES      25
25      c    3      VIT      45
26      c    3    MATCH      98

如果需要,您可以在结果上设置索引:

result = result.set_index(['player', 'week'])

关于python - 在多索引数据框中查找列的最大值并返回其所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49906335/

相关文章:

python - 单击按钮后切换到打开的新浏览器 [Python][Selenium]

python - 在 numpy 中按间隔分割数组的简单方法

python - bool() 和 operator.truth() 有什么区别?

python - 在dask数据帧上使用groupby

python - 数据框中的百分位排名。 Pandas

python - 验证 Scrapy HTTP 代理

python - 有没有办法在 python 中做 HTTP PUT

python - Beautifulsoup for row 循环只运行一次?

python - 使用 Cnn 和 Lstm 提取图像字幕生成器的特征?

python - 按一列上的另一个数据框对数据框进行排序 - pandas