Pandas入门2(DataFunctions+Maps+groupby+sort_values)

文章目录

    • 3. Summary Functions and Maps
      • 3.1 Summary Functions 数据总结函数
        • 3.1.1 describe()
        • 3.1.2 mean(),median(),idxmax(),unique(),value_counts()
      • 3.2 Maps 映射
        • 3.2.1 map()
        • 3.2.2 apply()
        • 3.2.3 内置转换方法
    • 4. Grouping and Sorting
      • 4.1 Grouping 分组
        • 4.1.1 groupby()
        • 4.1.2 agg()
        • 4.1.3 multi_indexes
      • 4.2 sort_values() 排序

learn from https://www.kaggle.com/learn/pandas

上一篇:Pandas入门1(DataFrame+Series读写/Index+Select+Assign)
下一篇:Pandas入门3(dtype+fillna+replace+rename+concat+join)

3. Summary Functions and Maps

3.1 Summary Functions 数据总结函数

3.1.1 describe()

  • wine_rev.points.describe(),各种统计信息,数字信息总结
# 数字列的总结
count    129971.000000
mean         88.447138
std           3.039730
min          80.000000
25%          86.000000
50%          88.000000
75%          91.000000
max         100.000000
Name: points, dtype: float64
  • wine_rev.country.describe(),文字信息总结
# 文字类列的总结
count     129908
unique        43
top           US
freq       54504
Name: country, dtype: object

3.1.2 mean(),median(),idxmax(),unique(),value_counts()

  • wine_rev.points.mean(),均值,median(),中位数,idxmax(),最大数据的下标
  • wine_rev.country.unique(),不同的值多少个
array(['Italy', 'Portugal', 'US', 'Spain', 'France', 'Germany','Argentina', 'Chile', 'Australia', 'Austria', 'South Africa','New Zealand', 'Israel', 'Hungary', 'Greece', 'Romania', 'Mexico','Canada', nan, 'Turkey', 'Czech Republic', 'Slovenia','Luxembourg', 'Croatia', 'Georgia', 'Uruguay', 'England','Lebanon', 'Serbia', 'Brazil', 'Moldova', 'Morocco', 'Peru','India', 'Bulgaria', 'Cyprus', 'Armenia', 'Switzerland','Bosnia and Herzegovina', 'Ukraine', 'Slovakia', 'Macedonia','China', 'Egypt'], dtype=object)
  • wine_rev.country.value_counts(),各个值的计数
US                        54504
France                    22093
Italy                     19540
Spain                      6645
.....
Egypt                         1
China                         1
Name: country, dtype: int64

3.2 Maps 映射

3.2.1 map()

  • wine_points_mean = wine_rev.points.mean()
  • wine_rev.points.map(lambda p : p-wine_points_mean),将数据变到均值上下(产生一个Series,原DF数据没变)
0        -1.447138
1        -1.447138
2        -1.447138
3        -1.447138
4        -1.447138...   
129966    1.552862
129967    1.552862
129968    1.552862
129969    1.552862
129970    1.552862
Name: points, Length: 129971, dtype: float64

3.2.2 apply()

通过定义函数,使用apply对整个表进行转换,对每一行进行操作

def remean_points(row):row.points = row.points - wine_points_meanreturn row
wine_rev.apply(remean_points,axis='columns')

Note that map() and apply() return new, transformed Series and DataFrames, respectively.
They don’t modify the original data they’re called on.
上面两种方法都不会修改原始数据

3.2.3 内置转换方法

  • wine_rev.points - wine_points_mean,直接相减就可以,每个数据都会减去右边的单个value
0        -1.447138
1        -1.447138
2        -1.447138
3        -1.447138
4        -1.447138...   
129966    1.552862
129967    1.552862
129968    1.552862
129969    1.552862
129970    1.552862
Name: points, Length: 129971, dtype: float64
  • wine_rev.country + '-' + wine_rev.region_1,相等长度的两个Series操作,直接1v1对应起来
0                     Italy-Etna
1                            NaN
2           US-Willamette Valley
3         US-Lake Michigan Shore
4           US-Willamette Valley...          
129966                       NaN
129967                 US-Oregon
129968             France-Alsace
129969             France-Alsace
129970             France-Alsace
Length: 129971, dtype: object

4. Grouping and Sorting

4.1 Grouping 分组

4.1.1 groupby()

  • wine_rev.groupby('points').points.count()
points
80       397
81       692
82      1836
83      3025
84      6480
85      9530
86     12600
87     16933
88     17207
89     12226
90     15410
91     11359
92      9613
93      6489
94      3758
95      1535
96       523
97       229
98        77
99        33
100       19
Name: points, dtype: int64
  • wine_rev.groupby('points').price.min(),按得分分组,然后每组里面价格最低的
points
80      5.0
81      5.0
82      4.0
83      4.0
84      4.0
85      4.0
86      4.0
87      5.0
88      6.0
89      7.0
90      8.0
91      7.0
92     11.0
93     12.0
94     13.0
95     20.0
96     20.0
97     35.0
98     50.0
99     44.0
100    80.0
Name: price, dtype: float64
  • wine_rev.groupby('points').apply(lambda df : df.title.iloc[0]),按得分分组后,每个DataFrame的 title的第一行,代码产生的是一个Series
points
80     Viña Tarapacá 2015 Gran Reserva Chardonnay (Le...
81     Pura 8 2010 Grand Reserve Pinot Noir (Rapel Va...
82       Mémoires 2015 Rosé (Coteaux Varois en Provence)
83         Koyle 2015 Costa Pinot Noir (Colchagua Costa)
84     Three Brothers 2014 Zero Degree Dry Riesling (...
85     Casa Silva 2008 Gran Reserva Petit Verdot (Col...
86     Clarksburg Wine Company 2010 Chenin Blanc (Cla...
87                     Nicosia 2013 Vulkà Bianco  (Etna)
88                  Fattoria Sardi 2015 Rosato (Toscana)
89           David Fulton 2008 Petite Sirah (St. Helena)
90     Beaumont 2005 Hope Marguerite Chenin Blanc (Wa...
91     Le Riche 2003 Cabernet Sauvignon Reserve Caber...
92     Dopff & Irion 2004 Schoenenbourg Grand Cru Ven...
93     Claiborne & Churchill 2014 Twin Creeks Estate ...
94         Sandeman 2015 Quinta do Seixo Vintage  (Port)
95     Jasper Hill 2013 Georgia's Paddock Shiraz (Hea...
96                        Oremus 2005 Eszencia  (Tokaji)
97     Robert Weil 2014 Kiedrich Gräfenberg Trockenbe...
98     Chambers Rosewood Vineyards NV Rare Muscadelle...
99     Quilceda Creek 2008 Cabernet Sauvignon (Columb...
100    Chambers Rosewood Vineyards NV Rare Muscat (Ru...
dtype: object
  • wine_rev.groupby(['country','province']).apply(lambda df : df.loc[df.points.idxmax()])
    按照,先按国家分组、再按省份分组,每个组里得分最大的,产生的是一个DataFrame
    在这里插入图片描述

4.1.2 agg()

  • wine_rev.groupby(['country']).price.agg([len,min,max]),后面可以跟一些统计量
    在这里插入图片描述

4.1.3 multi_indexes

  • country_rev = wine_rev.groupby(['country','province']).description.agg([len]),多个特征的分组是多索引的
    在这里插入图片描述
  • country_rev.index,MultiIndex 多级索引
MultiIndex([('Argentina',  'Mendoza Province'),('Argentina',             'Other'),(  'Armenia',           'Armenia'),('Australia',   'Australia Other'),('Australia',   'New South Wales'),('Australia',   'South Australia'),('Australia',          'Tasmania'),('Australia',          'Victoria'),('Australia', 'Western Australia'),(  'Austria',           'Austria'),...(       'US',        'Washington'),(       'US', 'Washington-Oregon'),(  'Ukraine',           'Ukraine'),(  'Uruguay',         'Atlantida'),(  'Uruguay',         'Canelones'),(  'Uruguay',           'Juanico'),(  'Uruguay',        'Montevideo'),(  'Uruguay',          'Progreso'),(  'Uruguay',          'San Jose'),(  'Uruguay',           'Uruguay')],names=['country', 'province'], length=425)
  • 转换多级索引为普通索引,cr = country_rev.reset_index(),需赋值给一个新的DF
    在这里插入图片描述

4.2 sort_values() 排序

上面例子可以看出,输出都是按照 index 排序的,我们有时希望按值排序

  • cr.sort_values(by='len'),默认升序
    在这里插入图片描述
  • cr.sort_values(by='len',ascending=False),降序(升序=False)
  • cr.sort_index(),恢复按 index 升序
    在这里插入图片描述
  • 按多个值进行排序,cr.sort_values(by=['country', 'len']),先按国家字符串升序,然后按长度升序
    在这里插入图片描述
  • cr.sort_values(by=['country', 'len'],ascending=[False,True]),还可分别指定,每个特征是升序还是降序
    在这里插入图片描述

上一篇:Pandas入门1(DataFrame+Series读写/Index+Select+Assign)
下一篇:Pandas入门3(dtype+fillna+replace+rename+concat+join)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/475807.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Adobe和苹果相互推诿 不支持Flash谁之过?

针对苹果CEO史蒂夫乔布斯 (Steve Jobs)的指责,Adobe CTO凯文林奇(Kevin Lynch)日前给予回应,称苹果iPad不支持Flash完全是苹果的错。上周三,苹果发布了业内期待已久的平板电脑iPad,但由于不支持 Flash而遭到了用户抱怨。对此&…

linux视频在windows播放器,适用于Windows和Linux的免费多媒体播放器SMPlayer 18.6.0发布 - 爱绿豆...

SMPlayer是一个很好的 MPlayer 电影播放程序前端,可以支持大部分的视频和音频文件。它支持音频轨道切换,允许调节亮度、对比度、色调、饱和度、伽玛值,按照倍速、4倍速等多种速度回放,还可以进行音频和字幕延迟调整以同步音频和字…

LeetCode 393. UTF-8 编码验证(位运算)

1. 题目 UTF-8 中的一个字符可能的长度为 1 到 4 字节,遵循以下的规则: 对于 1 字节的字符,字节的第一位设为0,后面7位为这个符号的unicode码。对于 n 字节的字符 (n > 1),第一个字节的前 n 位都设为1&#xff0c…

OA 办公系统 模块设计

--连接主数据库 use Master go --如果数据库simpleoa 存在,则先删除simpleoa。 if exists (select * from sysdatabases where namesimpleoa) drop database simpleoa go--创建simpleoa数据库 create database simpleoa go-- use simpleoa go--创建用户表 create…

通过java理解linux,Java继承的理解

继承:1)概念把多个类中相同的成员给提取出来定义到一个独立的类中。然后让这多个类和该独立的类产生一个关系,这多个类就具备了这些内容。这个关系叫继承。1.1)定义类时,通过“继承”一个现有的类,子类可以具有父类中的所有属性和…

LeetCode 373. 查找和最小的K对数字(自定义优先队列BFS)

1. 题目 给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。 定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。 找到和最小的 k 对数字 (u1,v1), (u2,v2) … (uk,vk)。 示例 1: 输入: nums1 [1,7,11], nums2 [2,4,…

Android中使用Thread线程出现的问题

很多初入Android或Java开发的新手对Thread、Looper、Handler和Message仍然比较迷惑,衍生的有HandlerThread、java.util.concurrent、Task、AsyncTask由于目前市面上的书籍等资料都没有谈到这些问题,今天Android123就这一问题做更系统性的总结.  Androi…

linux防火墙的复规则,Centos下iptables防火墙规则编辑方法 - YangJunwei

今天整理一下Centos下iptables防火墙规则的保存、清除等编辑方法。如已经安装,请跳过。$ yum install iptables二、查看 iptables 防火墙已有规则以下四种方法任选其一即可。$ service iptables status$ /etc/init.d/iptables status (此方法为上一方法的路径执行版…

Blend设计VSM

Silverlight中的ControlTemplate(1)-概念 Silverlight中的ControlTemplate(2)-概念 Silverlight中的ControlTemplate(3)-Blend设计ControlTemplate 上一篇我是通过Blend简单的演示如何修改ControlTemplate,这一篇关注VSM这个部分。 概念的东…

Pandas入门3(dtype+fillna+replace+rename+concat+join)

文章目录5. dtype 数据类型6. Missing data 缺失值6.1 查找缺失值 pd.isnull(),pd.notnull()6.2 填补缺失值 fillna(),replace()7. Renaming and Combining 重命名、合并7.1 Renaming 重命名7.2 Combining 合并数据learn from https://www.kaggle.com/l…

Linux连接状态为syn_recv,linux 服务器 syn*** 大量SYN_RECV状态处理

1、查看连接状态netstat -nat | awk /^tcp/{S[$NF]}END{for (a in S) print a,S[a]}SYN_RECV表示正在等待处理的请求数;ESTABLISHED表示正常数据传输状态;TIME_WAIT表示处理完毕,等待超时结束的请求数。状态:描述CLOSED&#xff1…

LeetCode 388. 文件的最长绝对路径(不用栈,前缀和)

1. 题目 假设我们以下述方式将我们的文件系统抽象成一个字符串: 字符串 "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" 表示: dirsubdir1subdir2file.ext目录 dir 包含一个空的子目录 subdir1 和一个包含一个文件 file.ext 的子目录 subdir2 。 字符串 "dir\n…

使用Delphi自带的TDockTabSet组件实现停靠功能(Jeremy North)

源地址:http://edn.embarcadero.com/article/33446 摘要: Instructions on how to use the TDockTabSet component to make advanced docking user interfaces. Introduction This article discusses the use of the TDockTabSet component that was originally int…

linux下面 r和 n的区别,【冷知识】关于/r与/n以及 /r/n 的区别总结

首先:\r就是"回到行首",\n就是"到下一行"即:\r是回车,\n是换行,前者使光标到行首,后者使光标下移一格。通常用的Enter是两个加起来的,即\r\n直接这么说你可能没啥感觉,但是真正到了编码…

LeetCode 417. 太平洋大西洋水流问题(BFS/DFS)

文章目录1. 题目2. 解题2.1 BFS 广度优先搜索2.2 DFS 深度优先搜索1. 题目 给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。 “太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。 规定水流只能按照上、下、左、右四个方…

用jdbc连接各数据库驱动

sql server 2000下的连接串:DRIVER"com.microsoft.jdbc.sqlserver.SQLServerDriver";URL"jdbc:microsoft:sqlserver://localhost:1433;databaseNamessoDemo;usersa;password1"; sql server 2005下的连接串:private static final Str…

安装linux出现基础系统出错,Linux系统出错提示信息详解

ERROR PCI: cannot allocate(无法指派)这样的错误有许多,他们主要在启动系统时出现。他们有一个共同的起因:错误的电源管理行为。罪魁祸首是一个叫做ACPI的东西,即高级配置与电源接口。尽管他是一种电源管理标准,但在十几年的时间…

vCard 格式

最近在做联系人的一些功能,当然是有必要了解一下vCard文件的格式,格式大致如下: vCard 2.1: 1: BEGIN:VCARD 2: VERSION:2.1 3: N:Gump;Forrest 4: FN:Forrest Gump 5: ORG:Bubba Gump Shrimp Co. 6: TITLE:Shrimp Man 7: TEL;WORK;V…

c语言基本数据类型常量,C语言基础学习基本数据类型-变量和常量

变量和常量什么是变量和常量?有些数据在程序运行前就预先设定,并在运行过程中不发生变化,称之为常量;有些数据在程序运行中可能发生变化或被赋值,称之为变量。使用变量前必须先声明一个变量。变量定义的语法是&#xf…

C++ 下一代标准库 tr1中默认的哈希 FNV hash

FNV是 Glenn Fowler, Landon Curt Noll, and Phong Vo 三人的缩写。 FNV-1 哈希算法的核心思想如下: hash offset_basisfor each octet_of_data to be hashed hash hash * FNV_prime hash hash xor octet_of_data return hash实现源码 uint32_t fnv_hash…