CHAPTER 5
Getting Started with pandas
文章目录
pandas
包含数据结构和数据操作工具,通常与NumPy
和SciPy
等数值计算工具、statsmodel
和scikit-learn
等分析库以及matplotlib
等数据可视化库一起使用。
之后的笔记里,这样导入pandas(也是惯例了):
import pandas as pd
另外可以导入Series和DataFrame,因为这两个经常被用到:
from pandas import Series, DataFrame
5.1 pandas的数据结构(Introduction to pandas Data Structures)
Pandas有三大数据结构,Series、DataFrame以及Panel。
- Series(一维数据)
- DataFrame(二维数据)
- Panel(三维结构数据/面板数据)
注释:对于Panel,会很少使用,通常会使用MultiIndex这种结构解决三维数据表示问题,暂不介绍了就!
5.1.1 Series
这里series
我就不翻译成序列了,因为之前的所有笔记里,我都是把sequence
翻译成序列的
series
是一个像数组一样的一维序列,并伴有一个数组表示label,叫做index。创建一个series的方法也很简单:
>>>obj = pd.Series([4, 7, -5, 3])
>>>obj
0 4
1 7
2 -5
3 3
dtype: int64
可以看到,左边表示index,右边表示对应的value。可以通过value和index属性查看:
>>>obj.values
array([ 4, 7, -5, 3], dtype=int64)
>>>obj.index # like range(4)
RangeIndex(start=0, stop=4, step=1)
当然我们也可以自己指定index的label:
>>>obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
>>>obj2
d 4
b 7
a -5
c 3
dtype: int64
>>>obj2.index
Index(['d', 'b', 'a', 'c'], dtype='object')
可以用index的label来选择:
>>>obj2['a']
-5
>>>obj2['d'] = 6
>>>obj2[['c', 'a', 'd']]
c 3
a -5
d 6
dtype: int64
这里[‘c’, ‘a’, ‘d’]其实被当做了索引,尽管这个索引是用string构成的。
使用numpy
函数或类似的操作,会保留index-value
的关系:
>>>obj2[obj2 > 0]
d 6
b 7
c 3
dtype: int64
>>>obj2 * 2
d 12
b 14
a -10
c 6
dtype: int64
>>>np.exp(obj2)
d 403.428793
b 1096.633158
a 0.006738
c 20.085537
dtype: float64
另一种看待series
的方法,它是一个长度固定,有顺序的dict
,从index映射到value。在很多场景下,可以当做dict来用:
>>>'b' in obj2
True
>>>'e' in obj2
False
还可以直接用现有的dict
来创建series
:
>>>sdata = {
'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
>>>obj3 = pd.Series(sdata)
>>>obj3
Ohio 35000
Oregon 16000
Texas 71000
Utah 5000
dtype: int64
series
中的index其实就是dict中排好序的keys。我们也可以传入一个自己想要的顺序:
>>>states = ['California', 'Ohio', 'Oregon', 'Texas']
>>>obj4 = pd.Series(sdata, index=states)
>>>obj4
California NaN
Ohio 35000.0
Oregon 16000.0
Texas 71000.0
dtype: float64
顺序是按states里来的,但因为没有找到california,所以是NaN。NaN表示缺失数据,用之后我们提到的话就用missing或NA来指代。pandas
中的isnull
和notnull
函数可以用来检测缺失数据:
>>>pd.isnull(obj4)
California