它含有使数据清洗和分析⼯ 作变得更快更简单的数据结构和操作⼯具。pandas
经常和其它⼯具⼀同使⽤,如数值计算⼯具NumPy
和
SciPy
,分析库statsmodels和
scikit-learn
,和数据可视化库
matplotlib
。
pandas是基于NumPy
数组构建的,特别是基于数组的函数和不使⽤
for循环的数据处理。虽然pandas采⽤了⼤量的
NumPy
编码⻛格,但⼆者最⼤的不同是pandas
是专⻔为处理表格和混杂数据设计的。大多数pandas用户都会引入
import pandas as pd
这个约定。因此,只要在代码中看到
pd.
,就得想到这是
pandas
。因为Series和
DataFrame
⽤的次数⾮常多,所以将其引⼊本地命名空
间中会更⽅便。即
from pandas import Series, DataFrame
。
![](https://img-blog.csdnimg.cn/ad3b72f78c6841f9880ee9fb5dca0ee7.gif)
要使⽤pandas,你⾸先就得熟悉它的两个主要数据结构:Series和DataFrame,本次介绍series。
Series
Series是一种类似于一维数组的对象,它由一组数据以及一组与之相关的索引组成。最简单的Series产生如下
In [11]: obj = pd.Series([4, 7, -5, 3])
In [12]: obj
Out[12]:
0 4
1 7
2 -5
3 3
dtype: int64
Series的字符串表现形式为:索引在左边,值在右边。由于我们 没有为数据指定索引,于是会⾃动创建⼀个0到N-1(N为数据的 ⻓度)的整数型索引。还可以设置索引:
In [15]:obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
In [16]:obj2
Out[16]:
d 4
b 7
a -5
c 3
dtype: int64
In [17]:obj2.values
Out[17]:array([ 4, 7, -5, 3], dtype=int64)
In [18]:obj2.index
Out[18]:Index(['d', 'b', 'a', 'c'], dtype='object')
与普通
NumPy
数组相⽐,你可以通过索引的⽅式选取
Series中的单个或⼀组值,就算
使⽤
NumPy
函数或类似
NumPy
的运算(如根据布尔型数组进⾏过滤、标量乘法、应⽤数学函数等)都会保留索引值的链接
:
In [19]: obj2['a']
Out[19]: -5
In [20]: obj2['d']=6
In [21]: obj2[['c','a','d']]
Out[21]:
c 3
a -5
d 6
dtype: int64
In [22]: obj2*2
Out[22]:
d 12
b 14
a -10
c 6
dtype: int64
如果数据被存放在⼀个
Python
字典中,也可以直接通过这个字典来创建Series,如若索引值找不到对应的值则会直接补充NaN值:
In [26]: sdata={'Ohio':35000, 'Texas':71000, 'Oregon':16000, 'Utah': 5000}
In [27]: obj3=pd.Series(sdata)
In [28]: obj3
Out[28]:
Ohio 35000
Oregon 16000
Texas 71000
Utah 5000
dtype: int64
查找缺失值时
pandas
的
isnull和notnull
函数可⽤于检测缺失数据。
In [26]: sdata={'California':,'Ohio':35000, 'Texas':71000, 'Oregon':16000, 'Utah': 5000}
In [27]: obj4=pd.Series(sdata)
In [28]: pd.isnull(obj4)
Out[28]:
California True
Ohio False
Oregon False
Texas False
dtype: bool
In [29]: pd.notnull(obj4)
Out[29]:
California False
Ohio True
Oregon True
Texas True
dtype: bool
#Series中的⽅法
In [34]: obj4.isnull()
Out[34]:
California True
Ohio False
Oregon False
Texas False
dtype: bool
Series
对象本身及其索引都有⼀个
name
属性,该属性跟
pandas其他的关键功能关系⾮常密切:
In [38]: obj4.name = 'population'
In [39]: obj4.index.name = 'state'
In [40]: obj4
Out[40]:
state
California NaN
Ohio 35000.0
Oregon 16000.0
Texas 71000.0
Name: population, dtype: float64
Series
的索引还可以通过赋值的⽅式就地修改:
In [41]: obj
Out[41]:
0 4
1 7
2 -5
3 3
dtype: int64
In [42]: obj.index=['Bob','Steve','Jeff','Ryan']
In [43]: obj
Out[43]:
Bob 4
Steve 7
Jeff -5
Ryan 3
dtype: int64