這個(gè)學(xué)期起初的時(shí)候?qū)σ恍〇|西有所了解過(guò)纠炮,就跳過(guò)很多東西吧,把一些自己認(rèn)為重要的做出筆記灯蝴,看了昨天的那東西恢口,截圖搞得自己現(xiàn)在都犯糊涂,以后有機(jī)會(huì)再把主要的原理和知識(shí)點(diǎn)搞出來(lái)吧穷躁,畢竟現(xiàn)在我也不是很懂耕肩。 今天弄pandas, 字?jǐn)?shù)不多问潭,但好長(zhǎng)猿诸。
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 10)
pd.set_option('display.max_rows', 10)
不弄也沒(méi)事,有些數(shù)據(jù)反而不好顯示狡忙,但知道有這么個(gè)設(shè)置吧
import pandas? as pd
s3 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
pd.Series(np.arange(0, 9))????? 基本形式就是這樣
pd.Series(np.linspace(0, 9, 10))??? 等步長(zhǎng) 以10為底? Series注意大寫(xiě)梳虽,自帶索引
s6 = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4})?? 字典創(chuàng)建
size, shape, uniqueness, and counts of values ? ? 以s.sise方式調(diào)用
# count() returns the number of non-Na N values?? s.count()返回非空數(shù)組
# all unique values? ? ? ? ? s.unique()? 以及啥s.value_counts()
Peeking at data with heads, tails, and take? ? ? s.head(n = 3)? ? s.tail(n = 3)
其中s.take([0, 3, 9])? take返回特定的行,用行索引值
s5.loc[12]? 按標(biāo)簽找值? ? s5.loc[[12, 10]]??? 多個(gè)標(biāo)簽找值
s5.iloc[1]? ? 按索引找值? s5.iloc[[0, 2]]
?ix兩個(gè)都可以 ???? 如s3.ix[['a', 'c']]? ? s3.ix[[1, 2]]
但兩個(gè)pandas相加會(huì)以索引相同的相加
nda = np.array([1, 2, 3, 4, np.Na N])? ? nda.mean() ? 會(huì)得到空值灾茁,pandas會(huì)忽略空值計(jì)算均值
s.mean(skipna=False)
學(xué)表達(dá)式? logical Results = s > 5 ? ?? s[logical Results]
或者更短 ? s[s > 5]
s[s > 5 and s < 8]? 是錯(cuò)誤的語(yǔ)法?
s[(s > 5) & (s < 8)]?? 才是正確的怖辆,不用and/or???? 用? &/ |?? 否則會(huì)錯(cuò)? s[s < 2].any()
Reindexing a Series?
s = pd.Series(np.random.randn(5))
s.index = ['a', 'b', 'c', 'd', 'e']
combined = pd.concat([s1, s2])?? 索引類(lèi)型必須一直,否則出現(xiàn)空值
s2.index = s2.index.values.astype(int)?? 換數(shù)據(jù)類(lèi)型
s2.reindex(['a', 'f'], fill_value=0)
s3.reindex(np.arange(0,7), method='ffill')
切片操作:? s[0:6:2]? ?? 意思是 查找位置 索引 0, 2, 4的值
相當(dāng)于??? s.iloc[[0, 2, 4]]
還有? s[:5:2]? ? s[4::2]? 4開(kāi)始步長(zhǎng)為2? s[::-1]? 反轉(zhuǎn)删顶。? s[4::-2]? 倒數(shù)第四個(gè)起
s[-3:]? ? 最后三個(gè)? ? s[-4:-1]??? equivalent to s.tail(4).head(3)
以上是Series的竖螃,接下來(lái)時(shí)DataFrame
The pandas Data Frame Object
import numpy as np?
import pandas as pd
pd.DataFrame(np.array([[10, 11], [20, 21]]))??? 自帶索引 列名? 若無(wú)指定
"{0}, {1}".format(df.columns[0], df.columns[1])
df.columns = ['c1', 'c2']? 重命名列
create a Data Frame with named columns and rows
df = pd.Data Frame(np.array([[0, 1], [2, 3]]),columns=['c1', 'c2'],index=['r1', 'r2'])
sp500 = pd.read_csv("data/sp500.csv",index_col='Symbol',usecols=[0, 2, 3, 7])指定索引列,并制定只選取哪些列
Selecting columns of a DataFrame?? 選取某些列
?? sp500[[1, 2]].head()?? 1逗余,2列的頭部(前5行)
get price column by name? ? sp500['Price']? sp500[['Price', 'Sector']]
選行:
sp500[:5]? 前5行? ? ? ? sp500['ABT':'ACN']? ? sp500.loc['MMM']? sp500.loc[['MMM', 'MSFT']]
sp500.iloc[[0, 2]]? ? sp500.ix[['MSFT', 'ZTS']]? sp500.ix[[10, 200, 450]]
sp500.at['MMM', 'Price']???? 坐標(biāo)值
sp500[sp500.Price < 100]
r = sp500[(sp500.Price < 10) &(sp500.Price > 0)] [['Price']]? 條件下只選擇顯示price列
Renaming columns?? 重命名列
df = sp500.rename(columns={'Book Value': 'Book Value'})
sp500.rename(columns={'Book Value': 'Book Value'},inplace=True)? 參數(shù)的作用是在原始列中重命名實(shí)現(xiàn)
增加插入列
copy['Twice Price'] = sp500.Price * 2?? 新列
copy.insert(1, 'Twice Price', sp500.Price * 2)?? 插入位置特咆,名字,值
rcopy = sp500[0:3][['Price']].copy()
置換列的內(nèi)容:copy.Price = sp500.Price * 2? 不增加新列
del copy['Book Value']?? 刪某列
popped = copy.pop('Sector')
afterdrop = copy.drop(['Sector'], axis = 1)?? 1指列
apending rows with .append()? 增加行用這個(gè)函數(shù)
appended = df1.append(df2)
df1.append(df3, ignore_index=True) 參數(shù)不加會(huì)引起索引的不連續(xù) ,即各自索引拼接而已腻格,
pd.concat([df1, df2])? 也可以這樣
df2_2.insert(3, 'Foo', pd.Series(0, index=df2.index))?? 插入列
r = pd.concat([df1, df2_2], keys=['df1', 'df2'])
效果:
pd.concat([df3, df4], axis=1)?? 按列拼接
df4_2.insert(1, 'Sector', pd.Series(1, index=df4_2.index))
df6 = sp500[2:5][[0,1]]?? 顯示2到5行 1画拾,2列
pd.concat([df5, df6], join='inner', axis=1)? 注意join參數(shù),還有幾個(gè)
afterdrop = ss.drop(['ABT', 'ACN'])? 把行里面的選定標(biāo)簽給去掉了
subset.loc['MMM', 'Price'] = 10
subset.loc['ABBV', 'Price'] = 20? 改變值
subframe = df[1:4][['B', 'C']]
Resetting and reindexing
reset_sp500 = sp500.reset_index()?? 把原本的索引列變?yōu)槠胀?/p>
reset_sp500.set_index('Symbol')???? 將普通列設(shè)置為索引列
reindexed = subset.reindex(index=['MMM', 'ABBV', 'FOO'])? 重新設(shè)置行索引的位置和內(nèi)容
subset.reindex(columns=['Price','Book Value','New Col'])? 可以用于列的索引標(biāo)簽
Hierarchical indexing?? 叫層次化索引吧菜职,英語(yǔ)不好
reindexed = sp500.reset_index()? 先將源索引貶職青抛,
multi_fi = reindexed.set_index(['Sector', 'Symbol'])? 在設(shè)置多個(gè)索引,按順序的這是
one_mon_hist.mean()?? 默認(rèn)為列的均值
one_mon_hist.mean(axis=1)??? 計(jì)算為行的均值
one_mon_hist[['MSFT', 'AAPL']].min()
pd.Series([1, 2, 3, 4]).cumprod()?? 連乘
pd.Series([1, 2, 3, 4]).cumsum()? 累加
one_mon_hist.describe()
s.unique()
s.value_counts()? ? 每一個(gè)唯一值得個(gè)數(shù)酬核。
pd.read_csv()? function:這個(gè)函數(shù)用于讀取數(shù)據(jù)
msft = pd.read_csv("data/msft.csv", index_col=0) 指定索引
msft.dtypes? 查看數(shù)據(jù)類(lèi)型之后
msft = pd.read_csv("data/msft.csv",dtype = { 'Volume' : np.float64})? 改變數(shù)據(jù)類(lèi)型
df = pd.read_csv("data/msft.csv",header=0,names=['open', 'high', 'low','close', 'volume', 'adjclose']) 修飾列名蜜另,header=0 表示跳過(guò)首行,必須有嫡意,不然以后會(huì)出問(wèn)題 可能
df2 = pd.read_csv("data/msft.csv",usecols=['Date', 'Close'],index_col=['Date'])? 指定列举瑰,索引
df2.to_csv("data/msft_modified.csv", index_label='date')? 存儲(chǔ)數(shù)據(jù)
df = pd.read_table("data/msft.csv", sep=',')?? 分隔符為,的文件
df.to_csv("data/msft_piped.txt", sep='|')
df = pd.read_csv("data/msft2.csv", skiprows=[0, 2, 3])? 跳過(guò)那幾行
df = pd.read_csv("data/msft_with_footer.csv",skip_footer=2,engine = 'python') 跳過(guò)最后兩行
pd.read_csv("data/msft.csv", nrows=3)? 只讀取前3行
pd.read_csv("data/msft.csv", skiprows=100, nrows=5,header=0,names=['open', 'high', 'low', 'close', 'vol','adjclose'])? 以上的整合蔬螟,就不寫(xiě)意思了
df = pd.read_excel("data/stocks.xlsx")
aapl = pd.read_excel("data/stocks.xlsx", sheetname='aapl') 讀取指定表
df.to_excel("data/stocks2.xls")??? 存儲(chǔ)
df.to_excel("data/stocks_msft.xls", sheet_name='MSFT')
from pandas import Excel Writer
with Excel Writer("data/all_stocks.xls") as writer:
aapl.to_excel(writer, sheet_name='AAPL')
df.to_excel(writer, sheet_name='MSFT') ? 多個(gè)表的操作
df_from_json = pd.read_json("data/stocks.json")
從web讀取html 數(shù)據(jù)
url = "http://www.fdic.gov/bank/individual/failed/banklist.html"
banks = pd.read_html(url)
首先import? Html5Lib
df = pd.Data Frame(np.random.randn(8, 3),index=pd.date_range('1/1/2000', periods=8),columns=['A', 'B', 'C'])
這是從web讀取
df = pd.read_csv("http://ichart.yahoo.com/table.csv?s=MSFT&" +"a=5&b=1&c=2014&" +"d=5&e=30&f=2014&" +"g=d&ignore=.csv") ? ? 反正沒(méi)弄成此迅,在編譯器上報(bào)網(wǎng)址錯(cuò)誤
但要記住這個(gè)方法,旧巾,或記住有這個(gè)方法
Reading and writing from/to SQL? databases? 這一站等過(guò)幾天學(xué)習(xí)生sql的時(shí)候在回過(guò)來(lái) 看吧
從遠(yuǎn)程數(shù)據(jù)服務(wù)器上讀取數(shù)據(jù)
import pandas.io.data as web?? 改了耸序,,會(huì)報(bào)錯(cuò)
start = datetime.datetime(2012, 1, 1)
end = datetime.datetime(2014, 1, 27)
yahoo = web.Data Reader('MSFT', 'yahoo', start, end)
goog = web.Data Reader("MSFT", 'google', start, end)
aapl = pd.io.data.Options('AAPL', 'yahoo')? 函數(shù)
data = aapl.get_all_data()??? 不知道能成不
data.loc[(80, slice(None), 'put'), :].iloc[0:5, 0:4]? 能理解意思上面的基礎(chǔ)操作就沒(méi)有白學(xué)習(xí)
msft_calls = pd.io.data.Options('MSFT', 'yahoo').get_call_data(expiry=expiry)
expiry = datetime.date(2015, 1, 17)
aapl_calls = aapl.get_call_data(expiry=expiry)
gdp = web.Data Reader("GDP", "fred",datetime.date(2012, 1, 1),datetime.date(2014, 1, 27))
還可以下載數(shù)據(jù):
Tidying Up Your Data? 清洗臟數(shù)據(jù)