【问题标题】:How can repetitive rows of data be collected in a single row in pandas?如何将重复的数据行收集到熊猫的一行中?
【发布时间】:2022-10-13 16:40:46
【问题描述】:

我有一个数据集,其中包含 NBA 球员每场比赛的平均统计数据。一些球员的统计数据会重复,因为他们在赛季中曾在不同的球队效力。

例如:

      Player       Pos  Age Tm    G     GS   MP      FG
8   Jarrett Allen   C   22  TOT  28     10  26.2     4.4
9   Jarrett Allen   C   22  BRK  12     5   26.7     3.7
10  Jarrett Allen   C   22  CLE  16     5   25.9     4.9

我想平均 Jarrett Allen 的统计数据并将它们放在一行中。我怎样才能做到这一点?

【问题讨论】:

  • 你试过groupby吗?
  • 我是初学者,先生,Idk如何去做。你能给我一些关于这方面的资料吗?
  • 语法是:df.groupby([ <要保留的列列表> ]).mean()。在答案中添加了一个示例。
  • 您确定要对所有这些行进行平均吗?从数学上讲,对所有这些行求平均值是没有意义的,因为 a) "TOT" 行已经是他本赛季效力过的所有球队的平均数据,b) 你会取 @ 的平均值987654323@和FG

标签: python pandas dataframe data-science


【解决方案1】:

您可以groupby 并使用agg 来获取平均值。对于非数字列,我们取第一个值:

df.groupby('Player').agg({k: 'mean' if v in ('int64', 'float64') else 'first'
                          for k,v in df.dtypes[1:].items()})

输出:

              Pos  Age   Tm          G        GS         MP        FG
Player                                                               
Jarrett Allen   C   22  TOT  18.666667  6.666667  26.266667  4.333333

注意。词典理解的内容:

{'Pos': 'first',
 'Age': 'mean',
 'Tm': 'first',
 'G': 'mean',
 'GS': 'mean',
 'MP': 'mean',
 'FG': 'mean'}

【讨论】:

  • 打扰一下,我可以问一下这段代码的解释吗? “agg”内部发生了什么?或者你能给我发关于这个主题的链接吗?
  • agg 使用函数聚合值。在这里,我使用字典来告诉它每列要计算哪个聚合(平均值或第一个)。我在答案中添加了指向文档的链接。字典是使用列类型计算的。如果数字(int/float)我们用'mean'聚合,否则我们取第一个值。如果您需要更多详细信息,请告诉我。
  • 如果想使用相同的方法但在每一列中指定要执行的操作,则可以执行以下操作df = df.groupby('Player').agg({'Pos': 'first', 'Age': 'mean', 'Tm': 'first', 'G': 'mean', 'GS': 'mean', 'MP': 'mean', 'FG': 'mean'})
【解决方案2】:
x = [['a', 12, 5],['a', 12, 7], ['b', 15, 10],['b', 15, 12],['c', 20, 1]]

import pandas as pd
df = pd.DataFrame(x, columns=['name', 'age', 'score'])
print(df)
print('-----------')

df2 = df.groupby(['name', 'age']).mean()
print(df2)

输出:

  name  age  score
0    a   12      5
1    a   12      7
2    b   15     10
3    b   15     12
4    c   20      1
-----------
          score
name age       
a    12       6
b    15      11
c    20       1

【讨论】:

    【解决方案3】:

    选项1

    如果考虑 OP 在问题df 中共享的数据框,则以下内容将完成工作

    df_new = df.groupby('Player').agg(lambda x: x.iloc[0] if pd.api.types.is_string_dtype(x.dtype) else x.mean())
    
    [Out]:
                  Pos   Age   Tm          G        GS         MP        FG
    Player                                                                
    Jarrett Allen   C  22.0  TOT  18.666667  6.666667  26.266667  4.333333
    

    这个使用:

    让我们用一个新的数据框 df2 来测试它,Player 列中有更多元素。

    import numpy as np
    
    df2 = pd.DataFrame({'Player': ['John Collins', 'John Collins', 'John Collins', 'Trae Young', 'Trae Young', 'Clint Capela', 'Jarrett Allen', 'Jarrett Allen', 'Jarrett Allen'],
                        'Pos': ['PF', 'PF', 'PF', 'PG', 'PG', 'C', 'C', 'C', 'C'],
                        'Age': np.random.randint(0, 100, 9),
                        'Tm': ['ATL', 'ATL', 'ATL', 'ATL', 'ATL', 'ATL', 'TOT', 'BRK', 'CLE'],
                        'G': np.random.randint(0, 100, 9),
                        'GS': np.random.randint(0, 100, 9),
                        'MP': np.random.uniform(0, 100, 9),
                        'FG': np.random.uniform(0, 100, 9)})
    
    [Out]:
              Player Pos  Age   Tm   G  GS         MP         FG
    0   John Collins  PF   71  ATL  75  39  16.123225  77.949756
    1   John Collins  PF   60  ATL  49  49  30.308092  24.788401
    2   John Collins  PF   52  ATL  33  92  11.087317  58.488575
    3     Trae Young  PG   72  ATL  20  91  62.862313  60.169282
    4     Trae Young  PG   85  ATL  61  77  30.248551  85.169038
    5   Clint Capela   C   73  ATL   5  67  45.817690  21.966777
    6  Jarrett Allen   C   23  TOT  60  51  93.076624  34.160823
    7  Jarrett Allen   C   12  BRK   2  77  74.318568  78.755869
    8  Jarrett Allen   C   44  CLE  82  81   7.375631  40.930844
    

    如果在 df2 上测试操作,将得到以下结果

    df_new2 = df2.groupby('Player').agg(lambda x: x.iloc[0] if pd.api.types.is_string_dtype(x.dtype) else x.mean())
    
    [Out]:
                  Pos        Age   Tm          G         GS         MP         FG
    Player                                                                       
    Clint Capela    C  95.000000  ATL  30.000000  98.000000  46.476398  17.987104
    Jarrett Allen   C  60.000000  TOT  48.666667  19.333333  70.050540  33.572896
    John Collins   PF  74.333333  ATL  50.333333  52.666667  78.181457  78.152235
    Trae Young     PG  57.500000  ATL  44.500000  47.500000  46.602543  53.835455
    

    选项 2

    根据所需的输出,假设只想按玩家分组(独立于 AgeTm),一个更简单的解决方案是按如下方式分组并传递 .mean()

    df_new3 = df.groupby('Player').mean()
    
    [Out]:
    
                    Age          G        GS         MP        FG
    Player                                                       
    Jarrett Allen  22.0  18.666667  6.666667  26.266667  4.333333
    

    笔记:

    • 先前操作的输出不会显示非数字列(玩家名称除外)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-04
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多