草庐IT

Pandas - 10.1 聚合groupby-agg/aggreagte

陈天睡懒觉 2023-10-16 原文

可以与groupby一起使用的方法或函数

count / np.count_nonzero 统计频数(不包含NaN值)
size 统计频数 (包含NaN值)
mean / np.mean 求平均值
std / np.std 样本标准差
min /np.min 最小值
quantile(q=0.25) / np.percentile(q=0.25) 较小四分位数
quantile(q=0.5) / np.percentile(q=0.5) 中位数
quantile(q=0.75) / np.percentile(q=0.75) 较大四分位数
max / np.max 最大值
sum / np.sum 求和
var / np.var 无偏方差
sem / scipy.stats.sem 平均值的无偏方差
describe / scipy.stats.describe 统计信息描述
frist 返回第一行
last 返回最后一行
nth 返回第n行

import pandas as pd
df = pd.read_csv('data/gapminder.tsv', sep='\t')

continent_describe = df.groupby('continent').lifeExp.describe()
print(continent_describe)

'''
           count       mean        std     min       25%      50%       75%  \
continent                                                                     
Africa     624.0  48.865330   9.150210  23.599  42.37250  47.7920  54.41150   
Americas   300.0  64.658737   9.345088  37.579  58.41000  67.0480  71.69950   
Asia       396.0  60.064903  11.864532  28.801  51.42625  61.7915  69.50525   
Europe     360.0  71.903686   5.433178  43.585  69.57000  72.2410  75.45050   
Oceania     24.0  74.326208   3.795611  69.120  71.20500  73.6650  77.55250   

              max  
continent          
Africa     76.442  
Americas   80.653  
Asia       82.603  
Europe     81.757  
Oceania    81.235  
'''

聚合函数

除了上面列出的函数,可以调用agg或aggregate方法传入想用的聚合函数。

  • 传入其他库的函数
  • 传入自定义的函数

传入其他库的函数

import numpy as np

cont_le_agg = df.groupby('continent').lifeExp.agg(np.mean)
print(cont_le_agg)

'''
continent
Africa      48.865330
Americas    64.658737
Asia        60.064903
Europe      71.903686
Oceania     74.326208
Name: lifeExp, dtype: float64
'''

cont_le_agg2 = df.groupby('continent').lifeExp.aggregate(np.mean)
print(cont_le_agg2)

'''
continent
Africa      48.865330
Americas    64.658737
Asia        60.064903
Europe      71.903686
Oceania     74.326208
Name: lifeExp, dtype: float64
'''

自定义函数

def my_mean(values):
    n = len(values)
    sum = 0
    for value in values:
        sum += value
    return (sum/n)

agg_my_mean = df.groupby('continent').lifeExp.aggregate(my_mean)
print(agg_my_mean)

'''
continent
Africa      48.865330
Americas    64.658737
Asia        60.064903
Europe      71.903686
Oceania     74.326208
Name: lifeExp, dtype: float64
'''

带有多个参数的自定义聚合函数,第一个参数是值序列,其他参数作为关键字传入agg

def my_mean_diff(values, diff_value):
    n = len(values)
    sum =0
    for value in values:
        sum += value
    mean = sum/n
    return (mean - diff_value)

global_mean = df.lifeExp.mean()
print(global_mean) # 59.47443936619713

agg_mean_diff = df.groupby('year').lifeExp.agg(my_mean_diff, diff_value=global_mean)
print(agg_mean_diff)

'''
year
1952   -10.416820
1957    -7.967038
1962    -5.865190
1967    -3.796150
1972    -1.827053
1977     0.095718
1982     2.058758
1987     3.738173
1992     4.685899
1997     5.540237
2002     6.220483
2007     7.532983
Name: lifeExp, dtype: float64
'''

同时传入多个函数

  • 对于一个序列计算多个聚合函数,将它们放入一个python列表,再将列表传入agg
  • 对多个序列分别使用不同的聚合函数,将字典传入agg

一个序列计算多个聚合函数

gdf = df.groupby('year').lifeExp.agg([np.mean, np.std, np.count_nonzero])
print(gdf)

'''
           mean        std  count_nonzero
year                                     
1952  49.057620  12.225956          142.0
1957  51.507401  12.231286          142.0
1962  53.609249  12.097245          142.0
1967  55.678290  11.718858          142.0
1972  57.647386  11.381953          142.0
1977  59.570157  11.227229          142.0
1982  61.533197  10.770618          142.0
1987  63.212613  10.556285          142.0
1992  64.160338  11.227380          142.0
1997  65.014676  11.559439          142.0
2002  65.694923  12.279823          142.0
2007  67.007423  12.073021          142.0
'''

gdf = df.groupby('year').lifeExp.\
    agg([np.mean, np.std, np.count_nonzero]).\
    rename(columns={'mean':'avg',
                   'count_nonzero':'count',
                   'std':'std_dev'}).reset_index()

print(gdf)

'''
    year        avg    std_dev  count
0   1952  49.057620  12.225956  142.0
1   1957  51.507401  12.231286  142.0
2   1962  53.609249  12.097245  142.0
3   1967  55.678290  11.718858  142.0
4   1972  57.647386  11.381953  142.0
5   1977  59.570157  11.227229  142.0
6   1982  61.533197  10.770618  142.0
7   1987  63.212613  10.556285  142.0
8   1992  64.160338  11.227380  142.0
9   1997  65.014676  11.559439  142.0
10  2002  65.694923  12.279823  142.0
11  2007  67.007423  12.073021  142.0
'''

多个序列分别使用不同的聚合函数,针对DataFrame

gdf_dict = df.groupby('year').agg({
    'lifeExp':'mean',
    'pop':'median',
    'gdpPercap':'median'})
print(gdf_dict)

'''
        lifeExp         pop    gdpPercap
year                                    
1952  49.057620   3943953.0  1968.528344
1957  51.507401   4282942.0  2173.220291
1962  53.609249   4686039.5  2335.439533
1967  55.678290   5170175.5  2678.334741
1972  57.647386   5877996.5  3339.129407
1977  59.570157   6404036.5  3798.609244
1982  61.533197   7007320.0  4216.228428
1987  63.212613   7774861.5  4280.300366
1992  64.160338   8688686.5  4386.085502
1997  65.014676   9735063.5  4781.825478
2002  65.694923  10372918.5  5319.804524
2007  67.007423  10517531.0  6124.371109

'''

有关Pandas - 10.1 聚合groupby-agg/aggreagte的更多相关文章

  1. 由于 libgmp.10.dylib 的问题,Ruby 2.2.0 无法运行 - 2

    我刚刚安装了带有RVM的Ruby2.2.0,并尝试使用它得到了这个:$rvmuse2.2.0--defaultUsing/Users/brandon/.rvm/gems/ruby-2.2.0dyld:Librarynotloaded:/usr/local/lib/libgmp.10.dylibReferencedfrom:/Users/brandon/.rvm/rubies/ruby-2.2.0/bin/rubyReason:Incompatiblelibraryversion:rubyrequiresversion13.0.0orlater,butlibgmp.10.dylibpro

  2. ruby - ri 有空文件 – Ubuntu 11.10, Ruby 1.9 - 2

    我正在运行Ubuntu11.10并像这样安装Ruby1.9:$sudoapt-getinstallruby1.9rubygems一切都运行良好,但ri似乎有空文档。ri告诉我文档是空的,我必须安装它们。我执行此操作是因为我读到它会有所帮助:$rdoc--all--ri现在,当我尝试打开任何文档时:$riArrayNothingknownaboutArray我搜索的其他所有内容都是一样的。 最佳答案 这个呢?apt-getinstallri1.8编辑或者试试这个:(非rvm)geminstallrdocrdoc-datardoc-da

  3. ruby-on-rails - gem install rmagick -v 2.13.1 错误 Failed to build gem native extension on Mac OS 10.9.1 - 2

    我已经通过提供MagickWand.h的路径尝试了一切,我安装了命令工具。谁能帮帮我?$geminstallrmagick-v2.13.1Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingrmagick:ERROR:Failedtobuildgemnativeextension./Users/ghazanfarali/.rvm/rubies/ruby-1.8.7-p357/bin/rubyextconf.rbcheckingforRubyversion>=1.8.5...yescheckingfor/

  4. ruby - Rails Elasticsearch 聚合 - 2

    不知何故,我似乎无法获得包含我的聚合的响应...使用curl它按预期工作:HBZUMB01$curl-XPOST"http://localhost:9200/contents/_search"-d'{"size":0,"aggs":{"sport_count":{"value_count":{"field":"dwid"}}}}'我收到回复:{"took":4,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":90,"max_score":0.0,"hits":[]},"a

  5. ruby - 安装 tiny_tds 在 mac os 10.10.5 上出现错误 - 2

    我正在使用macos,我想使用ruby​​驱动程序连接到sqlserver。我想使用tiny_tds,但它给出了缺少free_tds的错误,但它已经安装了。怎么能过这个?~brewinstallfreetdsWarning:freetds-0.91.112alreadyinstalled~sudogeminstalltiny_tdsBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtiny_tds:ERROR:Failedtobuildgemnativeextension.完整日志如下:/System

  6. ruby - rails 3.2.2(或 3.2.1)+ Postgresql 9.1.3 + Ubuntu 11.10 连接错误 - 2

    我正在使用PostgreSQL9.1.3(x86_64-pc-linux-gnu上的PostgreSQL9.1.3,由gcc-4.6.real(Ubuntu/Linaro4.6.1-9ubuntu3)4.6.1,64位编译)和在ubuntu11.10上运行3.2.2或3.2.1。现在,我可以使用以下命令连接PostgreSQLsupostgres输入密码我可以看到postgres=#我将以下详细信息放在我的config/database.yml中并执行“railsdb”,它工作正常。开发:adapter:postgresqlencoding:utf8reconnect:falsedat

  7. ruby-on-rails - 在 osx 10.9.3 上使用 RVM 安装 ruby​​-1.9.3-p547 时出错 - 2

    如何解决这个错误:$rvminstall1.9.3Searchingforbinaryrubies,thismighttakesometime.Nobinaryrubiesavailablefor:osx/10.9/x86_64/ruby-1.9.3-p547.Continuingwithcompilation.Pleaseread'rvmhelpmount'togetmoreinformationonbinaryrubies.Checkingrequirementsforosx.Certificatesin'/usr/local/etc/openssl/cert.pem'arealr

  8. c# - Ruby 等效于 C# Linq 聚合方法 - 2

    什么是Linq聚合方法的ruby​​等价物。它的工作原理是这样的varfactorial=new[]{1,2,3,4,5}.Aggregate((acc,i)=>acc*i);每次将数组序列中的值传递给lambda时,变量acc都会累积。 最佳答案 这在数学以及几乎所有编程语言中通常称为折叠。它是更普遍的变形概念的一个实例。Ruby从Smalltalk中继承了这个特性的名称,它被称为inject:into:(像aCollectioninject:aStartValueinto:aBlock一样使用。)所以,在Ruby中,它称为inj

  9. u盘安装系统(win10为例) - 2

    下载微PE工具箱进入官网下载微PE工具箱-下载 安装好后,打开微PE工具箱客户端,选择安装PE到U盘 PE壁纸可选择自己喜欢的壁纸,勾选上包含DOS工具箱,个性化盘符图标 下载原版系统进入网站下载镜像NEXT,ITELLYOU如果没有账号,注册一下就好进入选择开始使用选择win10 这里我们选择消费者版,用迅雷把BT种子下载下来 下面的两个盘符,是PE工具箱安装进U盘后,分成的盘符,注意EFI的盘符,这里面不能删东西,也不能添东西,另一个盘符可以当做正常的U盘空间使用,我们现在需要把下载下来的景象文件复制到正常的U盘空间中去 这个时候我们的系统U盘就只做好了 安装系统我们将U盘插入电脑,开机,

  10. ruby-on-rails - OSX 10.7.5 - Ruby on Rails LoadError : Could not open library 'sodium' : dlopen(sodium, 5) - 2

    输入rakedb:create后我得到:LoadError:Couldnotopenlibrary'sodium':dlopen(sodium,5):imagenotfound.Couldnotopenlibrary'libsodium.dylib':dlopen(libsodium.dylib,5):imagenotfound这里还有一些输出。/Users/Mao/.rvm/gems/ruby-2.0.0-p451/gems/ffi-1.9.3/lib/ffi/library.rb:133:in`blockinffi_lib'/Users/Mao/.rvm/gems/ruby-2.0

随机推荐