Pandas两个主要数据结构之一——Series
Series是一种类似于一维数组的对象,它由一组数据(各种Numpy数据类型)以及一组与之相关的数据标签(即索引)构成。
创建Series
-
如果没有为数据指定索引,就会自动创建0到N-1的整数型索引。
In [2]: obj = pd.Series([4, 7, -5, 3]) In [3]: obj Out[3]: 0 4 1 7 2 -5 3 3 dtype: int64 -
创建带有对各数据点进行标记索引的Series
In [6]: obj2 = pd.Series([1, 2, 3, 4], index=['d', 'b', 'c', 'a']) In [7]: obj2 Out[7]: d 1 b 2 c 3 a 4 dtype: int64 -
如果数据被存储在python字典中,也可以通过这个字典来创建Series
In [8]: data = {'x': 30000, 'y': 40000, 'z': 50000, 'w': 60000} In [9]: obj3 = pd.Series(data) In [10]: obj3 Out[10]: x 30000 y 40000 z 50000 w 60000 dtype: int64 # 若有索引未对应元素,则对应值为NaN In [11]: index = ['m', 'x', 'y', 'z'] In [12]: obj4 = pd.Series(data, index) In [13]: obj4 Out[13]: m NaN x 30000.0 y 40000.0 z 50000.0 dtype: float64
索引Series
-
可以通过Series的values和index属性获取其数组表示形式和索引对象。
In [14]: obj.values Out[14]: array([ 4, 7, -5, 3]) In [15]: obj.index Out[15]: RangeIndex(start=0, stop=4, step=1) -
可以通过索引来选取Series的某个值或一组值
In [16]: obj2['a'] Out[16]: 4 In [19]: obj2[['c', 'b', 'a']] Out[19]: c 3 b 2 a 4 dtype: int64 In [20]: obj2[2:] Out[20]: c 3 a 4 dtype: int64 -
Series也可以看作是一个定长的有序字典,因为它是索引值到数据值的一个映射。它可以用在很多原本需要字典参数的函数中:
In [21]: 'b' in obj2 Out[21]: True
Series的计算
-
Series的算术计算有一个重要特性:在算术运算中会自动对齐不同数据的索引,即在索引相同的值间进行计算。
In [8]: obj3 + obj4 Out[8]: m NaN w NaN x 60000.0 y 80000.0 z 100000.0 dtype: float64 In [9]: obj3 - obj4 Out[9]: m NaN w NaN x 0.0 y 0.0 z 0.0 dtype: float64 In [10]: obj3 * obj4 Out[10]: m NaN w NaN x 9.000000e+08 y 1.600000e+09 z 2.500000e+09 dtype: float64Numpy数组运算(如根据布尔型数组进行过滤、标量乘法、应用数学函数)都会保留索引与值之间的链接。
In [13]: obj2[obj2 > 0] Out[13]: d 4 b 7 a 3 dtype: int64
Series的一些其他操作
-
Pandas的innull和notnull函数可用于检测缺失数据:
In [21]: obj4.isnull() Out[21]: m True x False y False z False dtype: bool -
Series对象本身及索引都有一个name属性
In [23]: obj4.name = 'p' In [24]: obj4.index.name = 'q' In [25]: obj4 Out[25]: q m NaN x 30000.0 y 40000.0 z 50000.0 Name: p, dtype: float64