以時(shí)間或日期前作為索引的金融數(shù)據(jù)栅组,稱之為金融時(shí)間序列棕兼。每日股價(jià)就是比較有代表的例子。Python處理金融時(shí)間序列的主要工具是pandas庫(kù)圆存,其中兩個(gè)基礎(chǔ)的類,DataFrame和Series
某種意義上仇哆,pandas是基于numpy構(gòu)建的沦辙,在初始,要同時(shí)import兩個(gè)庫(kù)
import numpy as np
import pandas as pd
1. 創(chuàng)建dataframe對(duì)象
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
同時(shí)指定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. 函數(shù)調(diào)用
numpy的函數(shù)可以通用在DataFrame對(duì)象上
df1.sum()
>>> numbers 100
dtype: int64
df1.apply(lambda x:x**2) # 對(duì)每一行元素進(jìn)行l(wèi)ambda函數(shù)運(yùn)算
>>> df1
numbers
a 100
b 400
c 900
d 1600