金融时间序列(pandas基础一)

以时间或日期前作为索引的金融数据,称之为金融时间序列。每日股价就是比较有代表的例子。Python处理金融时间序列的主要工具是pandas库,其中两个基础的类,DataFrame和Series

某种意义上,pandas是基于numpy构建的,在初始,要同时import两个库

import numpy as np
import pandas as pd

1. 创建dataframe对象

Init signature: pd.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

使用字典
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
指定colums
 df2 = pd.DataFrame(np.random.randint(low=0,high=10,size=(5, 5)), 
                     columns=['a', 'b', 'c', 'd', 'e'])
>>> df2
    a   b   c   d   e
0   2   8   8   3   4
1   4   2   9   0   9
2   1   0   7   8   0
3   5   1   7   1   3
4   6   0   2   4   2
同时指定colums和index
df1 = pd.DataFrame([10,20,30,40],\
                    columns=['numbers'],\
                    index=['a','b','c','d'])

>>> df1
    numbers
a   10
b   20
c   30
d   40

2. 索引

移除了ix索引方式,支持但不推荐,建议使用iloc和loc方法

loc['columns']

按columns索引

df1.loc['c']

>>> numbers    30
Name: c, dtype: int64
iloc['index']

按index索引

df1.iloc[0] 

>>> numbers    10
Name: a, dtype: int64

3. 函数调用

numpy的函数可以通用在DataFrame对象上

df1.sum()

>>> numbers    100
dtype: int64
df1.apply(lambda x:x**2)    # 对每一行元素进行lambda函数运算

>>> df1
    numbers
a   100
b   400
c   900
d   1600

你可能感兴趣的:(金融时间序列(pandas基础一))