pandas
是一个 Python Data Analysis Library.在使用前 import pandas as pd
一.创建对象(产生数据)
pandas
中有三种基本结构:
Series:1D labeled homogeneously-typed array
DataFrame:General 2D labeled, size-mutable tabular structure with potentially heterogeneously-typed columns
Panel:General 3D labeled, also size-mutable array
1.Series
Series
是一维带标记的数组结构,可以存储任意类型的数据(整数,浮点数,字符串,Python
对象等等)。
作为一维结构,它的索引叫做 index
,基本调用方法为s = pd.Series(data, index=index)。
data
可以是以下结构:
- 字典
ndarray
- 标量
(1)字典:如果 data
是个 dict
,如果不给定 index
,那么 index
将使用 dict
的 key
排序之后的结果,如果给定了 index
,那么将会按照 index
给定的值作为 key
从字典中读取相应的 value
,如果 key
不存在,对应的值为 NaN
(not a number, Pandas
中的缺失默认值)
d = {'a' : 0., 'b' : 1., 'c' : 2.}
pd.Series(d)
(2)ndarray
或者list
s = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"])
s = pd.Series([1,3,5,np.nan,6,8])
(3)从标量值构造:
pd.Series(5., index=['a', 'b', 'c', 'd', 'e'])
2.DataFrame
通过传递一个 numpy array ,时间索引以及列标签来创建一个 DataFrame ,DataFrame
值要求每一列数据的格式相同
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
除了向 DataFrame
中传入二维数组,我们也可以使用字典传入数据,字典的每个 key
代表一列,其 value
可以是各种能够转化为 Series
的对象:
df2 = pd.DataFrame({'A' : 1.,
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo&#