摘要:
- 两种基本的数据结构 Series 和 DataFrame
介绍
参考网址: http://pandas.pydata.org/pandas-docs/stable/
两个基本的重要的数据结构
- Series
- DataFrame
Series
>>> import pandas as pd
Series 是一个一维带标签的数组,其中你能包含任意类型的数据。Series 是一个类,其构造函数如下:
>>> help(pd.Series.__init__)
Help on method __init__ in module pandas.core.series:
__init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False) unbound pandas.core.series.Series method
在创建 Series 对象的时候,一般需要提供数据,即 data,例如:
>>> ser = pd.Series(data = [100,200,300,400,500])
>>> ser
0 100
1 200
2 300
3 400
4 500
dtype: int64
也可以给数据加上标签:
>>> ser = pd.Series(data=[100,200,300,400,500], index=['tom','bob','nancy','dan','eric'])
>>> ser
tom 100
bob 200
nancy 300
dan 400
eric 500
dtype: int64
可以看到,当我们不给数据添加标签的时候,标签就自动的从零开始,直到 len(data)-1
。
上面的两个例子中,给出的 data 所有的元素都是同一个类型,即 int64,但其实它可以包含不同的类型,如下所示:
>>> ser = pd.Series(data=[100,'foo',300,'bar',500], index=['tom','bob','nancy','dan','eric'])
>>> ser
tom 100
bob foo
nancy 300
dan bar
eric 500
dtype: object
除了上面使用普通的列表作为 data 的值外, 还可以使用, narry 字典 数(scale)来对其进行赋值。
获取标签对应的值
可以通过标签获得所对应的值:
>>> ser['nancy']
300
也可以使用 loc 方法来通过标签获取值,loc 即 location:
>