Series的简单使用
pandas有Series和Pandas两大主要的数据结构,本篇主要是介绍Series。
Series是一种类似于一维数组的对象,它由一组数据(各种Numpy数据类型)以及一组与之相关的数据标签(即索引)构成。
创建Series
- 如果没有为数据指定索引,就会自动创建0到N-1的整数型索引。
In [4]: obj = pd.Series([4, 7, -5, 3])
In [5]: obj
Out[5]:
0 4
1 7
2 -5
3 3
dtype: int64
- 可以通过Series的values和index属性获取其数组表示形式和索引对象。
In [6]: obj.index
Out[6]: RangeIndex(start=0, stop=4, step=1)
In [7]: obj.values
Out[7]: array([ 4, 7, -5, 3])
- 创建带有对各数据点进行标记索引的Series
In [8]: obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'c', 'a'])
- 通过索引来选取Series的某个值或一组值
In [9]: obj2['a']
Out[9]: 3
In [10]: obj2[['c', 'a', 'd']]
Out[10]:
c -5
a 3
d 4
dtype: int64
In [11]: obj2[2:]
Out[11]:
c -5
a 3
dtype: int64
- 如果数据被存储在python字典中,也可以通过这个字典来创建Series
In [15]: sdata = {'x': 30000, 'y': 40000, 'z': 50000, 'w': 60000}
In [16]: obj3 = pd.Series(sdata)
In [17]: obj3
Out[17]:
x 30000
y 40000
z 50000
w 60000
dtype: int64
In [18]: sindex = ['m', 'x', 'y', 'z']
In [19]: obj4 = pd.Series(sdata, sindex)
In [20]: obj4
Out[20]:
m NaN
x 30000.0
y 40000.0
z 50000.0
dtype: float64
sdata中和sindex索引相匹配那3个值会被找出来并放到相应的位置上,'m'的值找不到,因此结果为NaN(在pandas中用于表示缺失和NA值)。
Series运算
- Numpy数组运算(如根据布尔型数组进行过滤、标量乘法、应用数学函数)都会保留索引与值之间的链接。
In [13]: obj2[obj2 > 0]
Out[13]:
d 4
b 7
a 3
dtype: int64
- Series也可以看作是一个定长的有序字典,因为它是索引值到数据值的一个映射。它可以用在很多原本需要字典参数的函数中:
In [14]: 'b' in obj2
Out[14]: True
- Pandas的innull和notnull函数可用于检测缺失数据:
In [21]: obj4.isnull()
Out[21]:
m True
x False
y False
z False
dtype: bool
- Series的一个重要功能是:在算术运算中会自动对齐不同数据的索引。
In [22]: obj3 + obj4
Out[22]:
m NaN
w NaN
x 60000.0
y 80000.0
z 100000.0
dtype: float64
- 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
本文详细介绍了Pandas库中的Series数据结构,包括其创建方式(默认索引、自定义索引),通过索引选取和操作值,以及与Numpy数组的运算。还涉及了如何处理缺失值和设置Series对象及其索引的名称。
651

被折叠的 条评论
为什么被折叠?



