【问题标题】:group one column according to another column and sum of third column根据另一列和第三列的总和对一列进行分组
【发布时间】:2021-05-08 13:56:38
【问题描述】:

数据框如下所示:

df = pd.DataFrame({'name':["a"," b", "c","d", "e","a"," a", "a"," b", "c","d", "e","a"," a"],
       'gender': ["male", "female", "female", "female", "male","male","male","female","female", 
                  "female", "male","male","male", "male"],
      'year':[2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019],
      'month':[1, 12, 4, 3, 6, 7, 2, 4, 5, 1, 12, 4, 3, 6 ],
      'count':[100, 30, 10, 90, 34, 100, 30, 10, 90, 34, 100, 30, 10, 90]})

显示姓名、性别、出生年月、人数。

例如,2005 年 1 月有 100 个婴儿名为“a”。我想找到男性和女性的前 10 个常用名字,如下所示:

df.sort_values(['gender','count'],ascending=False,inplace=True)
male = df[df['gender']=='male']['name'].head(10).to_list()
female = df[df['gender']=='female']['name'].head(10).to_list()
results = pd.DataFrame({'Male':pd.Series(male),'Female':pd.Series(female)})
print (results)

但显然它给出了重复的金额,例如 5 a 而不是 a 的总金额。我需要总结它们,例如我们在 2005 年有 100 个“a”,在 2009 年有 100 个“a”等等。所以我们总共需要把它们加起来就像 100+ 100 和。最终的结果必须像 a 是男性,并且在 10 年内总共有 500 人被命名为 a 等等。

【问题讨论】:

  • 你是按年还是按月分组?
  • 我需要总金额。前 2005 年所有月份有多少个“a”?以及在所有年份有多少

标签: python pandas dataframe


【解决方案1】:

首先为count 列聚合sum,然后选择malefemaleSeries.nlargest,并返回名称的索引值:

s = df.groupby(['gender','name'])['count'].sum()

results = pd.DataFrame({'Male':pd.Series(s.loc['male'].nlargest(10).index),
                        'Female':pd.Series(s.loc['female'].nlargest(10).index)})
print (results)

  Male Female
0    a      b
1    d      d
2    e      c
3  NaN      a

【讨论】:

  • 谢谢你这是我问的
  • @nemo92world 那么为什么要接受另一个答案呢?是意外吗?
【解决方案2】:

我认为您正在寻找多个 groupby:

by_year = df.groupby(['year', 'gender', 'name']).agg({'count': 'sum'})
print(by_year)

total = by_year.groupby(['gender', 'name']).agg({'count': 'sum'})
print(total)

如果不是,请进一步说明预期结果。

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2021-11-01
    • 2015-10-29
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多