1. Series数组
Series 是一个类数组的数据结构,同时带有标签(lable)或者说索引(index)。数据结构
1.1 下边生成一个最简单的Series对象,由于没有给Series指定索引,因此此时会使用默认索引(从0到N-1)。函数
# 引入Series和DataFrame
In [16]: from pandas import Series,DataFrame In [17]: import pandas as pd In [18]: ser1 = Series([1,2,3,4]) In [19]: ser1 Out[19]: 0 1 1 2 2 3 3 4 dtype: int64
1.2 当要生成一个指定索引的Series 时候,能够这样: spa
# 给index指定一个list
In [23]: ser2 = Series(range(4),index = ["a","b","c","d"]) In [24]: ser2 Out[24]: a 0 b 1 c 2 d 3 dtype: int64
1.3 也能够经过字典来建立Series对象code
In [45]: sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} In [46]: ser3 = Series(sdata) # 能够发现,用字典建立的Series是按index有序的 In [47]: ser3 Out[47]: Ohio 35000 Oregon 16000 Texas 71000 Utah 5000 dtype: int64
在用字典生成Series的时候,也能够指定索引,当索引中值对应的字典中的值不存在的时候,则此索引的值标记为Missing,NA,而且能够经过函数(pandas.isnull,pandas.notnull)来肯定哪些索引对应的值是没有的。对象
In [48]: states = ['California', 'Ohio', 'Oregon', 'Texas'] In [49]: ser3 = Series(sdata,index = states) In [50]: ser3 Out[50]: California NaN Ohio 35000.0 Oregon 16000.0 Texas 71000.0 dtype: float64
# 判断哪些值为空
In [51]: pd.isnull(ser3)
Out[51]:
California True
Ohio False
Oregon False
Texas False
dtype: bool
In [52]: pd.notnull(ser3)
Out[52]:
California False
Ohio True
Oregon True
Texas True
dtype: bool
1.4 访问Series中的元素和索引:blog
# 访问索引为"a"的元素
In [25]: ser2["a"] Out[25]: 0 # 访问索引为"a","c"的元素 In [26]: ser2[["a","c"]] Out[26]: a 0 c 2 dtype: int64 # 获取全部的值 In [27]: ser2.values Out[27]: array([0, 1, 2, 3]) # 获取全部的索引 In [28]: ser2.index Out[28]: Index([u'a', u'b', u'c', u'd'], dtype='object')
1.5 简单运算索引
在pandas的Series中,会保留NumPy的数组操做(用布尔数组过滤数据,标量乘法,以及使用数学函数),并同时保持引用的使用数学
In [34]: ser2[ser2 > 2] Out[34]: a 64 d 3 dtype: int64 In [35]: ser2 * 2 Out[35]: a 128 b 2 c 4 d 6 dtype: int64 In [36]: np.exp(ser2) Out[36]: a 6.235149e+27 b 2.718282e+00 c 7.389056e+00 d 2.008554e+01 dtype: float64
1.6 Series的自动对齐pandas
Series的一个重要功能就是自动对齐(不明觉厉),看看例子就明白了。 差很少就是不一样Series对象运算的时候根据其索引进行匹配计算。
# ser3 的内容
In [60]: ser3 Out[60]: Ohio 35000 Oregon 16000 Texas 71000 Utah 5000 dtype: int64 # ser4 的内容 In [61]: ser4 Out[61]: California NaN Ohio 35000.0 Oregon 16000.0 Texas 71000.0 dtype: float64 # 相同索引值的元素相加 In [62]: ser3 + ser4 Out[62]: California NaN Ohio 70000.0 Oregon 32000.0 Texas 142000.0 Utah NaN dtype: float64
1.7 命名
Series对象自己,以及索引都有一个 name 属性
In [64]: ser4.index.name = "state" In [65]: ser4.name = "population" In [66]: ser4 Out[66]: state California NaN Ohio 35000.0 Oregon 16000.0 Texas 71000.0 Name: population, dtype: float64