pandas是一个强大的Python数据分析的工具包。
pandas是基于NumPy构建的。
pandas的主要功能:
具备对其功能的数据结构DataFrame、Series
集成时间序列功能
提供丰富的数学运算和操作
灵活处理缺失数据
- 安装方法:pip install pandas
- 引用方法:import pandas as pd
------> 以下测试都是在ipython中 <------
Series
Series是一种类似于一维数组的对象,由一组数据和一组与之相关的数据标签(索引)组成
Series比较像列表(数组)和字典的结合体
1 import pandas as pd 2 3 a=pd.Series([12,34,56,87,9800]) 4 a 5 0 12 6 1 34 7 2 56 8 3 87 9 4 9800 10 dtype: int64 11 左边是数组的索引或者下标 12 13 14 #也可以自定义标签 15 b=pd.Series([445,234,12,688,33],index=list("abcds")) 16 b 17 a 445 18 b 234 19 c 12 20 d 688 21 s 33 22 dtype: int64 23 24 25 # 像字典一样取值 26 b["a"] 27 445 28 b[0] 29 445 30 31 32 #获取左侧的标签,返回的是一个数组 33 b.index 34 Index([\'a\', \'b\', \'c\', \'d\', \'s\'], dtype=\'object\') 35 36 37 #获取右侧的值 38 b.values 39 array([445, 234, 12, 688, 33], dtype=int64)
Series支持NumPy模块的特性
从ndarray创建Series:Series(arr)
1 import numpy as np 2 3 c=pd.Series(np.arange(10,15)) 4 c 5 0 10 6 1 11 7 2 12 8 3 13 9 4 14 10 dtype: int32
与标量运算
1 c*2 2 0 20 3 1 22 4 2 24 5 3 26 6 4 28 7 dtype: int32 8 9 c+c+c 10 0 30 11 1 33 12 2 36 13 3 39 14 4 42 15 dtype: int32 16 17 a+c 18 0 22 19 1 45 20 2 68 21 3 100 22 4 9814 23 dtype: int64
索引,切片(跟numpy切片一样,也是一个视图,不单独复制,在切片后的数据上修改,将影响原数据,要解决这个文图用copy方法)
1 c 2 0 10 3 1 11 4 2 12 5 3 345 6 4 14 7 dtype: int32 8 9 #花式索引 10 c[[0,2,4]] 11 0 10 12 2 12 13 4 14 14 dtype: int32 15 c[1:3] 16 1 11 17 2 12 18 dtype: int32 19 f=c[2:5] 20 f 21 2 12 22 3 345 23 4 14 24 dtype: int32 25 26 #修改f的值会修改c的值 27 f[3]=345 28 c 29 0 10 30 1 11 31 2 12 32 3 345 33 4 14 34 dtype: int32 35 e=c[1:4].copy() 36 37 #e中没有0这个索引,所以会像字典一样,增加一个索引0的值 38 e[0]=23 39 e[1]=255 40 e 41 1 255 42 2 12 43 3 345 44 0 23 45 dtype: int64 46 47 #这个时候的c不会被改变 48 c 49 0 10 50 1 11 51 2 12 52 3 345 53 4 14 54 dtype: int32
函数,布尔值过滤
1 c.max() 2 14 3 c[c>12] 4 3 13 5 4 14 6 dtype: int32 7 8 #取索引为0和索引为4的值 9 c[[True,False,False,False,True]] 10 0 10 11 4 14 12 dtype: int32
Series支持字典的特性
从字典创建Series:Series(dic)
1 import pandas as pd 2 a=pd.Series({"a":12,"b":23,"c":22,"e":2,"f":9}) 3 a 4 a 12 5 b 23 6 c 22 7 e 2 8 f 9 9 dtype: int64
in运算:’a’ in sr
1 # 在python的字典中,in运算是值键的判断,在pandas里是对标签的比较 2 3 "a" in a 4 True 5 6 "d" in a 7 False
键索引:sr[\'a\'], sr[[\'a\', \'b\', \'d\']]
1 a["c"] 2 22 3 4 5 # 花式索引 6 a[["a","c"]] 7 a 12 8 c 22 9 dtype: int64 10 11 12 # 也可以使用位置索引 13 a[1] 14 23 15 16 17 # 但是for 循环的每一项是对应的值而非索引 18 for i in a: 19 print(i) 20 12 21 23 22 22 23 2 24 9
get取值
1 a.get("c") 2 22 3 # 如果没有匹配项,则返回一个指定的默认值,如果不指定default,则啥也不返回,也不报错 4 5 a.get("werwe",default=0) 6 0
花式切片
1 # 这个切片的与列表不一样,这里顾前也顾尾,可以取到f标签 2 3 a[["a","c","f"]] 4 a 12 5 c 22 6 f 9 7 dtype: int64
整数索引和标签索引
1 import numpy as np 2 3 a=pd.Series(np.arange(10,25)) 4 a 5 0 10 6 1 11 7 2 12 8 3 13 9 4 14 10 5 15 11 6 16 12 7 17 13 8 18 14 9 19 15 10 20 16 11 21 17 12 22 18 13 23 19 14 24 20 dtype: int32 21 22 b=a[8:].copy() 23 b 24 8 18 25 9 19 26 10 20 27 11 21 28 12 22 29 13 23 30 14 24 31 dtype: int32 32 33 # 如果我们想拿b的最后一个值,按照我们之前的项目切片 34 b[-1] 35 --------------------------------------------------------------------------- 36 37 KeyError Traceback (most recent call last) 38 39 <ipython-input-40-122a9a7eadfa> in <module>() 40 1 # 如果我们想拿b的最后一个值,按照我们之前的项目切片 41 2 42 ----> 3 b[-1] 43 44 45 d:\program files (x86)\python35\lib\site-packages\pandas\core\series.py in __getitem__(self, key) 46 599 key = com._apply_if_callable(key, self) 47 600 try: 48 --> 601 result = self.index.get_value(self, key) 49 602 50 603 if not is_scalar(result): 51 52 53 d:\program files (x86)\python35\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 54 2475 try: 55 2476 return self._engine.get_value(s, k, 56 -> 2477 tz=getattr(series.dtype, \'tz\', None)) 57 2478 except KeyError as e1: 58 2479 if len(self) > 0 and self.inferred_type in [\'integer\', \'boolean\']: 59 60 61 pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value (pandas\_libs\index.c:4404)() 62 63 64 pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value (pandas\_libs\index.c:4087)() 65 66 67 pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5126)() 68 69 70 pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas\_libs\hashtable.c:14031)() 71 72 73 pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas\_libs\hashtable.c:13975)() 74 75 76 KeyError: -1 77 b[7] 78 --------------------------------------------------------------------------- 79 80 KeyError Traceback (most recent call last) 81 82 <ipython-input-41-b01957796a20> in <module>() 83 ----> 1 b[7] 84 85 86 d:\program files (x86)\python35\lib\site-packages\pandas\core\series.py in __getitem__(self, key) 87 599 key = com._apply_if_callable(key, self) 88 600 try: 89 --> 601 result = self.index.get_value(self, key) 90 602 91 603 if not is_scalar(result): 92 93 94 d:\program files (x86)\python35\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 95 2475 try: 96 2476 return self._engine.get_value(s, k, 97 -> 2477 tz=getattr(series.dtype, \'tz\', None)) 98 2478 except KeyError as e1: 99 2479 if len(self) > 0 and self.inferred_type in [\'integer\', \'boolean\']: 100 101 102 pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value (pandas\_libs\index.c:4404)() 103 104 105 pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value (pandas\_libs\index.c:4087)() 106 107 108 pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5126)() 109 110 111 pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas\_libs\hashtable.c:14031)() 112 113 114 pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas\_libs\hashtable.c:13975)() 115 116 117 KeyError: 7 118 119 b[8] 120 121 18
上边两个报错的原因是,在整数索引中,当既可以解释成下标,也可以解释成标签的话,那它就解释成标签,在上边的b中,前边的数字既是下标也是标签,比如第一行,0既是下标,也是标签,所以b[-1]被当作找标签为-1的项。b[7]也是同样的道理
iloc :定义使用下标来查找(这里的下标是从0开始的,第一个位置是0)
1 # 那如果我不知道别的信息,只想拿最后一个值 2 3 b.iloc[-1] 4 24 5 # b中下标从0开始,不是从8开始 6 7 b.iloc[4] 8 22 9 10 # b中下标从0开始,不是从8开始 11 b.iloc[[1,3,5]] 12 9 19 13 11 21 14 13 23 15 dtype: int32 16 17 # b中下标从0开始,不是从8开始 18 b.iloc[2:7] 19 10 20 20 11 21 21 12 22 22 13 23 23 14 24 24 dtype: int32
loc :定义使用标签来查找
1 b 2 8 18 3 9 19 4 10 20 5 11 21 6 12 22 7 13 23 8 14 24 9 dtype: int32 10 11 b.loc[10] 12 20 13 b.loc[10:13] 14 10 20 15 11 21 16 12 22 17 13 23 18 dtype: int32 19 20 21 b.loc[[10,13]] 22 10 20 23 13 23 24 dtype: int32 25 26 27 # 这里因为是按标签解释,所以切片是顾头也顾尾 28 b.loc[8:9] 29 8 18 30 9 19 31 dtype: int32
loc和iloc只是定义了定义了解释的方式,后边还是可以传索引值,切片等
数据对齐和数据缺失
1 a= pd.Series([12,23,34], index=[\'c\',\'a\',\'d\']) 2 a 3 c 12 4 a 23 5 d 34 6 dtype: int64 7 8 b = pd.Series([11,20,10], index=[\'d\',\'c\',\'a\',]) 9 b 10 d 11 11 c 20 12 a 10 13 dtype: int64 14 15 a.values+b.values 16 array([23, 43, 44], dtype=int64) 17 a+b 18 a 33 19 c 32 20 d 45 21 dtype: int64
在pandas里,使用NaN(Not a Number)来表示缺失数据。其值等于np.nan。内置的None值也会被当做NaN处理
1 a= pd.Series([11,20,10], index=[\'d\',\'c\',\'a\',]) 2 a 3 d 11 4 c 20 5 a 10 6 dtype: int64 7 8 b= pd.Series([11,20,10], index=[\'d\',\'c\',\'f\',]) 9 b 10 d 11 11 c 20 12 f 10 13 dtype: int64 14 15 c=a.add(b) 16 c 17 a NaN 18 c 40.0 19 d 22.0 20 f NaN 21 dtype: float64
pandas先保证索引对齐,,如果存在不同索引,则结果的索引也就是求两个索引的并集
1 # 如果我不想要nan这个缺失值,我想要找不到的用0来补充(比如计算工资,我这个月入职,年底统计工资的时候,我得到的总工资不会是nann) 2 3 # 普通的做法是 4 c["a"]=0 5 c 6 a 0.0 7 c 40.0 8 d 22.0 9 f 10.0 10 dtype: float64 11 12 # 那如果数据量大的话,单个去操作就麻烦 13 14 #当对应的索引不存在的时,补充一个0,这样就保证计算的时候,始终能相加(其中一个值是0),注意这里不是说在已经得到的结果中去将nan的项替换 15 c=a.add(b,fill_value=0) 16 c 17 a 10.0 18 c 40.0 19 d 22.0 20 f 10.0 21 dtype: float64 22 23 c=a.add(b,fill_value=100) 24 c 25 a 110.0 26 c 40.0 27 d 22.0 28 f 110.0 29 dtype: float64
加减乘除运算
1 a 2 d 11 3 c 20 4 a 10 5 dtype: int64 6 b 7 d 11 8 c 20 9 f 10 10 dtype: int64 11 12 # 相减运算 13 c=a.sub(b,fill_value=1) 14 c 15 a 9.0 16 c 0.0 17 d 0.0 18 f -9.0 19 dtype: float64 20 21 # 除法运算 22 c=a.div(b,fill_value=1) 23 c 24 a 10.0 25 c 1.0 26 d 1.0 27 f 0.1 28 dtype: float64 29 30 # 乘法运算 31 c=a.mul(b,fill_value=1) 32 c 33 a 10.0 34 c 400.0 35 d 121.0 36 f 10.0 37 dtype: float64
如何处理结果集中的缺失值
1 c=a+b 2 c 3 a NaN 4 c 40.0 5 d 22.0 6 f NaN 7 dtype: float64 8 9 # 去掉含有nan的项 10 c.dropna() 11 c 40.0 12 d 22.0 13 dtype: float64 14 15 # 填充缺失数据 16 c.fillna(0) 17 a 0.0 18 c 40.0 19 d 22.0 20 f 0.0 21 dtype: float64 22 23 # 返回布尔数组,缺失值对应为True 24 c[~c.isnull()] 25 c 40.0 26 d 22.0 27 dtype: float64 28 29 # 返回布尔数组,缺失值对应为False 30 c[c.notnull()] 31 c 40.0 32 d 22.0 33 dtype: float64
自定义函数
map(函数名)
1 import pandas as pd 2 3 a=pd.Series([3,4,5,2,21,3]) 4 a 5 0 3 6 1 4 7 2 5 8 3 2 9 4 21 10 5 3 11 dtype: int64 12 13 a.map(lambda x:x+100) 14 0 103 15 1 104 16 2 105 17 3 102 18 4 121 19 5 103 20 dtype: int64