groupby分组

import pandas as pd
import numpy as np
df=pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],'B' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],'C' : np.random.randn(8),'D' : np.random.randn(8)})
print(df)grouped=df.groupby('A')
print('-'*30)
print(grouped.count())
print('-'*30)
grouped=df.groupby(['A','B'])
print(grouped.count())print('-'*30)
# 通过函数分组
def get_letter_type(letter):if letter.lower() in 'aeiou':return 'a'else:return 'b'grouped=df.groupby(get_letter_type,axis=1)
print(grouped.count())
     A      B         C         D
0  foo    one  1.429387  0.643569
1  bar    one -0.858448 -0.213034
2  foo    two  0.375644  0.214584
3  bar  three  0.042284 -0.330481
4  foo    two -1.421967  0.768176
5  bar    two  1.293483 -0.399003
6  foo    one -1.101385 -0.236341
7  foo  three -0.852603 -1.718694
------------------------------B  C  D
A
bar  3  3  3
foo  5  5  5
------------------------------C  D
A   B
bar one    1  1three  1  1two    1  1
foo one    2  2three  1  1two    2  2
------------------------------a  b
0  1  3
1  1  3
2  1  3
3  1  3
4  1  3
5  1  3
6  1  3
7  1  3
se=pd.Series([1,2,3,4,5],[6,9,8,9,8])
print(se)se.groupby(level=0)
6    1
9    2
8    3
9    4
8    5
dtype: int64<pandas.core.groupby.generic.SeriesGroupBy object at 0x111b00040>
# 分组求和
grouped=se.groupby(level=0).sum()
print(grouped)
6    1
8    8
9    6
dtype: int64
df2=pd.DataFrame({'X':['A','B','A','B'],'Y':[1,2,3,4]})
print(df2)
   X  Y
0  A  1
1  B  2
2  A  3
3  B  4
# 按X分组,并查询A列的数据
grp=df2.groupby('X').get_group('A')
print(grp)
   X  Y
0  A  1
2  A  3

Pandas 多级索引

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
index=pd.MultiIndex.from_arrays(arrays,names=['first','second'])
print(index)
MultiIndex([('bar', 'one'),('bar', 'two'),('baz', 'one'),('baz', 'two'),('foo', 'one'),('foo', 'two'),('qux', 'one'),('qux', 'two')],names=['first', 'second'])
s=pd.Series(np.random.randn(8),index=index)
print(s)
first  second
bar    one       0.120979two      -0.440384
baz    one       0.515106two      -0.019882
foo    one       1.149595two      -0.369984
qux    one      -0.930438two       0.146044
dtype: float64
# 分组求和
grouped=s.groupby(level='first')
print(grouped.sum())
first
bar   -0.319405
baz    0.495224
foo    0.779611
qux   -0.784394
dtype: float64
grouped=df.groupby(['A','B'])
print(grouped.size())
A    B
bar  one      1three    1two      1
foo  one      2three    1two      2
dtype: int64
print(df)
     A      B         C         D
0  foo    one  1.429387  0.643569
1  bar    one -0.858448 -0.213034
2  foo    two  0.375644  0.214584
3  bar  three  0.042284 -0.330481
4  foo    two -1.421967  0.768176
5  bar    two  1.293483 -0.399003
6  foo    one -1.101385 -0.236341
7  foo  three -0.852603 -1.718694
print(grouped.describe().head())
              C                                                              \count      mean       std       min       25%       50%       75%
A   B
bar one     1.0 -0.858448       NaN -0.858448 -0.858448 -0.858448 -0.858448   three   1.0  0.042284       NaN  0.042284  0.042284  0.042284  0.042284   two     1.0  1.293483       NaN  1.293483  1.293483  1.293483  1.293483
foo one     2.0  0.164001  1.789526 -1.101385 -0.468692  0.164001  0.796694   three   1.0 -0.852603       NaN -0.852603 -0.852603 -0.852603 -0.852603   D                                                    \max count      mean       std       min       25%       50%
A   B
bar one   -0.858448   1.0 -0.213034       NaN -0.213034 -0.213034 -0.213034   three  0.042284   1.0 -0.330481       NaN -0.330481 -0.330481 -0.330481   two    1.293483   1.0 -0.399003       NaN -0.399003 -0.399003 -0.399003
foo one    1.429387   2.0  0.203614  0.622191 -0.236341 -0.016364  0.203614   three -0.852603   1.0 -1.718694       NaN -1.718694 -1.718694 -1.718694


75% max
A B
bar one -0.213034 -0.213034
three -0.330481 -0.330481
two -0.399003 -0.399003
foo one 0.423592 0.643569
three -1.718694 -1.718694

grouped=df.groupby('A')
grouped['C'].agg([np.sum,np.mean,np.std])
sum mean std
A
bar 0.477319 0.159106 1.080712
foo -1.570925 -0.314185 1.188767

字符串操作

import pandas as pd
import numpy as np
s=pd.Series(['A','b','c','D',np.nan])
print(s)
# 转小写
print(s.str.lower())# 转大写
print(s.str.upper())# 每个字符的长度
print(s.str.len())
0      A
1      b
2      c
3      D
4    NaN
dtype: object
0      a
1      b
2      c
3      d
4    NaN
dtype: object
0      A
1      B
2      C
3      D
4    NaN
dtype: object
0    1.0
1    1.0
2    1.0
3    1.0
4    NaN
dtype: float64
index=pd.Index([' Index','ru ',' men'])# 去掉空格
print(index.str.strip())# 去掉左边的空格
print(index.str.lstrip())
# 去掉右边的空格
print(index.str.rstrip())
Index(['Index', 'ru', 'men'], dtype='object')
Index(['Index', 'ru ', 'men'], dtype='object')
Index([' Index', 'ru', ' men'], dtype='object')
df=pd.DataFrame(np.random.randn(3,2),columns=['A a','B b'],index=range(3))
print(df)
        A a       B b
0  3.005273  0.486696
1  1.093889  1.054230
2 -2.846352  0.302465
# 列替换
print(df.columns.str.replace(' ','_'))
Index(['A_a', 'B_b'], dtype='object')
s=pd.Series(['a_b_C','c_d_e','f_g_h'])
print(s)
0    a_b_C
1    c_d_e
2    f_g_h
dtype: object
print(s.str.split('_'))
0    [a, b, C]
1    [c, d, e]
2    [f, g, h]
dtype: object
print(s.str.split('_',expand=True,n=1))
   0    1
0  a  b_C
1  c  d_e
2  f  g_h
s = pd.Series(['A','rumen','ru','rumen','xiao','zhan'])
print(s.str.contains('ru'))
0    False
1     True
2     True
3     True
4    False
5    False
dtype: bool
s=pd.Series(['a','a|b','a|c'])
print(s)
0      a
1    a|b
2    a|c
dtype: object
print(s.str.get_dummies(sep='|'))
   a  b  c
0  1  0  0
1  1  1  0
2  1  0  1

索引

s=pd.Series(np.arange(5),np.arange(5)[::-1],dtype='int64')
s
4    0
3    1
2    2
1    3
0    4
dtype: int64
print(s[s>2])
1    3
0    4
dtype: int64
# isin查询索引在某个范围
print(s.isin([1,3,4]))
4    False
3     True
2    False
1     True
0     True
dtype: bool
# 根据索引查询数据
print(s[s.isin([1,3,4])])
3    1
1    3
0    4
dtype: int64
# 构造一个联合索引的数据
s=pd.Series(np.arange(6),index=pd.MultiIndex.from_product([[1,2],['a','b','c']]))
print(s)
1  a    0b    1c    2
2  a    3b    4c    5
dtype: int64
print(s.iloc[s.index.isin([(1,'b'),(2,'c')])])
1  b    1
2  c    5
dtype: int64
# 构造一个时间序列
dates=pd.date_range('20200920',periods=8)
print(dates)
DatetimeIndex(['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23','2020-09-24', '2020-09-25', '2020-09-26', '2020-09-27'],dtype='datetime64[ns]', freq='D')
df=pd.DataFrame(np.random.randn(8,4),index=dates,columns=['A','B','C','D'])
print(df)
                   A         B         C         D
2020-09-20 -1.218522  2.067088  0.015009  0.158780
2020-09-21 -0.546837 -0.601178 -0.894882  0.172037
2020-09-22  0.189848 -0.910520  0.196186 -0.073495
2020-09-23 -0.566892  0.899193 -0.450925  0.633253
2020-09-24  0.038838  1.577004  0.580927  0.609050
2020-09-25  1.562094  0.020813 -0.618859 -0.515212
2020-09-26 -1.333947  0.275765  0.139325  1.124207
2020-09-27 -1.271748  1.082302  1.036805 -1.041206
# 查询A列数据
print(df['A'])
2020-09-20   -1.218522
2020-09-21   -0.546837
2020-09-22    0.189848
2020-09-23   -0.566892
2020-09-24    0.038838
2020-09-25    1.562094
2020-09-26   -1.333947
2020-09-27   -1.271748
Freq: D, Name: A, dtype: float64
# 查询小于0的数字,大于0的值默认被置为NaN
df.where(df<0)
A B C D
2020-09-20 -1.218522 NaN NaN NaN
2020-09-21 -0.546837 -0.601178 -0.894882 NaN
2020-09-22 NaN -0.910520 NaN -0.073495
2020-09-23 -0.566892 NaN -0.450925 NaN
2020-09-24 NaN NaN NaN NaN
2020-09-25 NaN NaN -0.618859 -0.515212
2020-09-26 -1.333947 NaN NaN NaN
2020-09-27 -1.271748 NaN NaN -1.041206
# 查询小于0的数字,大于0的值变成负数
print(df.where(df<0,-df))
                   A         B         C         D
2020-09-20 -1.218522 -2.067088 -0.015009 -0.158780
2020-09-21 -0.546837 -0.601178 -0.894882 -0.172037
2020-09-22 -0.189848 -0.910520 -0.196186 -0.073495
2020-09-23 -0.566892 -0.899193 -0.450925 -0.633253
2020-09-24 -0.038838 -1.577004 -0.580927 -0.609050
2020-09-25 -1.562094 -0.020813 -0.618859 -0.515212
2020-09-26 -1.333947 -0.275765 -0.139325 -1.124207
2020-09-27 -1.271748 -1.082302 -1.036805 -1.041206
# 查询小于0的数据,大于0的置为1000
print(df.where(df<0,1000))
                      A            B            C            D
2020-09-20    -1.218522  1000.000000  1000.000000  1000.000000
2020-09-21    -0.546837    -0.601178    -0.894882  1000.000000
2020-09-22  1000.000000    -0.910520  1000.000000    -0.073495
2020-09-23    -0.566892  1000.000000    -0.450925  1000.000000
2020-09-24  1000.000000  1000.000000  1000.000000  1000.000000
2020-09-25  1000.000000  1000.000000    -0.618859    -0.515212
2020-09-26    -1.333947  1000.000000  1000.000000  1000.000000
2020-09-27    -1.271748  1000.000000  1000.000000    -1.041206
# 构造一个10行3列的数据
df=pd.DataFrame(np.random.randn(10,3),columns=list('abc'))
print(df)
          a         b         c
0  1.761415  0.528009 -0.347271
1 -0.682149  0.353312  0.337229
2  1.080733 -0.272290  1.020335
3 -0.979681 -1.753745  0.836387
4  0.243748  2.085531 -0.993318
5 -1.041006  1.518130 -0.087383
6 -1.400354 -0.095196  3.043639
7 -0.835144  0.926415 -1.217102
8  0.326098  1.079906  0.156884
9  1.836618 -1.288516 -2.492620
# 查询a>b的数据
print(df.query('a>b'))
          a         b         c
0  1.761415  0.528009 -0.347271
2  1.080733 -0.272290  1.020335
3 -0.979681 -1.753745  0.836387
9  1.836618 -1.288516 -2.492620
# 查询c>b>a的数据
print(df.query('(c<b) & (b<a)'))
          a         b         c
0  1.761415  0.528009 -0.347271
9  1.836618 -1.288516 -2.492620

Pandas入门教程(四)相关推荐

  1. python使用教程pandas-十分钟搞定pandas(入门教程)

    本文是对pandas官方网站上<10Minutes to pandas>的一个简单的翻译,原文在这里.这篇文章是对pandas的一个简单的介绍,详细的介绍请参考:Cookbook .习惯上 ...

  2. python使用教程pandas-Python 数据处理库 pandas 入门教程基本操作

    pandas是一个Python语言的软件包,在我们使用Python语言进行机器学习编程的时候,这是一个非常常用的基础编程库.本文是对它的一个入门教程. pandas提供了快速,灵活和富有表现力的数据结 ...

  3. LittleVGL (LVGL)干货入门教程四之制作和使用中文汉字字库

    LittleVGL (LVGL)干货入门教程四之制作和使用中文汉字字库 前言: 阅读前,请确保你至少拥有以下条件: 已实现显示API(教程一已实现, 链接:LittleVGL (LVGL)入门教程一之 ...

  4. Python+Opencv图像处理新手入门教程(四):视频内容的读取与导出

    一步一步来吧 上一节: Python+Opencv图像处理新手入门教程(三):阈值与二值化 1.Intro 今天这节我们主要看怎么利用opencv读取并处理视频中的内容. 2.VideoCapture ...

  5. Python自动化办公:pandas入门教程

    在后台回复[阅读书籍] 即可获取python相关电子书~ Hi,我是山月. 今天给大家带来一个强大的朋友:pandas.如果你有许多数据分析任务的话,那你一定不能错过它. 由于它的内容比较多,因此会分 ...

  6. python做数据处理软件_程序员用于机器学习编程的Python 数据处理库 pandas 入门教程...

    入门介绍 pandas适合于许多不同类型的数据,包括: · 具有异构类型列的表格数据,例如SQL表格或Excel数据 · 有序和无序(不一定是固定频率)时间序列数据. · 具有行列标签的任意矩阵数据( ...

  7. (原创)LEON3入门教程(四):基于AMBA APB总线的七段数码管IP核设计

    摘要:这一小节将介绍下如何设计用户自定义的APB IP,并将IP嵌入到SOPC中去.一个APB IP核的主要分为三个部分:逻辑单元.寄存器单元和接口单元.所设计的IP是一个简单的七段数码管显示IP,只 ...

  8. docker 镜像修改的配置文件自动还原_原创 | 全网最实在的docker入门教程四

    作者:潘吉祥 上一篇我们学习了如何使用Dockerfile制作自己的镜像,不过这种方式更像纯粹的运维方式,作为开发者来说,未免有些小繁琐,一个不小心写错些命令就执行失败,我们还不知道错误在哪,这着实有 ...

  9. python画图颜色表示大小变化_python画图(线条颜色、大小、类型:点、虚线等)(图文详细入门教程四)...

    初衷 本人由于平常写论文需要输出一些结果图,但是苦于在网上搜python画图时,详细的教程非常多,但是就是找不到能马上解决自己问题那一行代码,所以打算写一些适合需求简单的朋友应急用的教程,应急就必须方 ...

最新文章

  1. Python IDE ——Anaconda+PyCharm的安装与配置
  2. 局域网通过专线上网的维护经验点滴
  3. linux父子进程同步实验,Linux-父子进程的简单同步
  4. 【图像处理】——正装照换底色Python
  5. Python读取文本文档转化成列表
  6. feign使用_【微服务】165:Feign的最佳使用方式
  7. 开发选gRPC还是HTTP
  8. 基于布谷鸟搜索算法的无线传感器网络覆盖优化
  9. 孙玄:大中台模式下如何构建复杂业务核心状态机组件
  10. 在线付费听音乐平台网站源码
  11. ST芯片烧录失败的原因分析及对策
  12. 09组团队项目-Beta冲刺-5/5
  13. ~ 按位取反运算解析
  14. ReactNative入门(一)——环境搭建及第一个RN项目—HelloWorld
  15. BQB PTS dongle不识别问题
  16. HIN 异构信息网络(Heterogeneous Information Network)
  17. Linux 音频驱动(五) ALSA音频驱动之PCM逻辑设备
  18. 转铁蛋白Tf功能化β-榄香烯-雷公藤红素/紫杉醇PLGA纳米粒/雷公藤甲素脂质体(化学试剂)
  19. Unity学习记录:使用触发器制作人物靠近物体后交互的方法
  20. CISP知识大纲思维导图

热门文章

  1. sqlite like通配符使用 -转
  2. ubuntu防火墙关闭命令-转
  3. 蓝桥杯 ADV-74 算法提高 计算整数因子
  4. LeetCode 51. N-Queens
  5. c语言编写自动生成密码,c语言密码生成.doc
  6. python入门基础系列八_03python—9个基础常识-python小白入门系列
  7. java 程序在Eclipse 或者 Linux 运行报 Unsupported major.minor version 51.0解决办法
  8. Git学习系列之如何正确且高效地将本地项目上传到Github(图文详解)
  9. Facebook斥资5亿美元 建设全风电数据中心
  10. 运算放大器相关参数基本知识(一)