【问题标题】:How to use groupby or pivot in this pandas dataframe in python [duplicate]如何在python的这个熊猫数据框中使用groupby或pivot [重复]
【发布时间】:2018-11-15 11:21:29
【问题描述】:

我有以下数据框:

name   state  teams      score

abc    NY      red         1
def    VA      yellow      9
ghi    MO      green       6
abc    WA      red         2
klm    IL      yellow      1
ghi    MN      green       8
def    VA      blue        3
xyz    NY      blue        5
abc    NY      blue        5
abc    NY      red         4
ghi    MN      green       7

我想为每个名称状态组合以这样的方式对数据进行分组,我希望每个团队的得分最低,例如在我们拥有的数据中: name 'abc', state 'NY' 和 team 'red' 有两个分数 1 和 4 那么这里“红色”队的最低分数是 1。

对于我们没有得分的球队,最低分可以是 0。

示例输出:

name  state   red  yellow  green blue
abc    NY      1    0      0      5
def    VA      0    9      0      3
ghi    MO      0    0      6      0
abc    WA      ....................
klm    IL      ....................
ghi    MN      0    0      7     0     
xyz    NY      0    0     0     5   

【问题讨论】:

    标签: python pandas group-by pivot-table pandas-groupby


    【解决方案1】:

    选项 1:使用 groupbyunstack

    使用first 获取一个值,并使用unstack 中的fill_value 参数将NaN 替换为零:

    df.groupby(['name','state','teams']).min()['score'].unstack(fill_value=0).reset_index()
    

    输出:

    teams name state  blue  green  red  yellow
    0      abc    NY     5      0    1       0
    1      abc    WA     0      0    2       0
    2      def    VA     3      0    0       9
    3      ghi    MN     0      8    0       0
    4      ghi    MO     0      6    0       0
    5      klm    IL     0      0    0       1
    6      xyz    NY     5      0    0       0
    

    选项 2:使用 pd.crosstab

    (pd.crosstab([df['name'],df['state']],df['teams'],df['score'],aggfunc='min')\
      .fillna(0)
      .astype(int)
      .reset_index())
    

    选项 3:使用 pd.pivot_table

    (pd.pivot_table(df,'score',['name','state'],'teams',aggfunc='min', fill_value=0)
       .reset_index())
    

    【讨论】:

    • first() 给出了可用的第一个分数,但是,无论数据框中分数的顺序如何,我都希望获得最低分数
    • @user9463814 为此尝试min()。更新的解决方案。
    猜你喜欢
    • 2016-10-09
    • 2020-09-08
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2013-12-19
    • 2021-04-30
    相关资源
    最近更新 更多