learning pandas

這個學期起初的時候對一些東西有所了解過,就跳過很多東西吧,把一些自己認為重要的做出筆記,看了昨天的那東西,截圖搞得自己現(xiàn)在都犯糊涂,以后有機會再把主要的原理和知識點搞出來吧,畢竟現(xiàn)在我也不是很懂。 今天弄pandas, 字數(shù)不多,但好長。

pd.set_option('display.notebook_repr_html', False)

pd.set_option('display.max_columns', 10)

pd.set_option('display.max_rows', 10)


不弄也沒事,有些數(shù)據(jù)反而不好顯示,但知道有這么個設置吧

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))??? 等步長 以10為底? Series注意大寫,自帶索引

s6 = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4})?? 字典創(chuàng)建

size, shape, uniqueness, and counts of values ? ? 以s.sise方式調用

# 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]? 按標簽找值? ? s5.loc[[12, 10]]??? 多個標簽找值

s5.iloc[1]? ? 按索引找值? s5.iloc[[0, 2]]
?ix兩個都可以 ???? 如s3.ix[['a', 'c']]? ? s3.ix[[1, 2]]



但兩個pandas相加會以索引相同的相加

nda = np.array([1, 2, 3, 4, np.Na N])? ? nda.mean() ? 會得到空值,pandas會忽略空值計算均值

s.mean(skipna=False)

學表達式? logical Results = s > 5 ? ?? s[logical Results]

或者更短 ? s[s > 5]

s[s > 5 and s < 8]? 是錯誤的語法?

s[(s > 5) & (s < 8)]?? 才是正確的,不用and/or???? 用? &/ |?? 否則會錯? 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])?? 索引類型必須一直,否則出現(xiàn)空值

s2.index = s2.index.values.astype(int)?? 換數(shù)據(jù)類型

s2.reindex(['a', 'f'], fill_value=0)

s3.reindex(np.arange(0,7), method='ffill')

切片操作:? s[0:6:2]? ?? 意思是 查找位置 索引 0, 2, 4的值

相當于??? s.iloc[[0, 2, 4]]

還有? s[:5:2]? ? s[4::2]? 4開始步長為2? s[::-1]? 反轉。? s[4::-2]? 倒數(shù)第四個起

s[-3:]? ? 最后三個? ? s[-4:-1]??? equivalent to s.tail(4).head(3)

以上是Series的,接下來時DataFrame

The pandas Data Frame Object

import numpy as np?

import pandas as pd

pd.DataFrame(np.array([[10, 11], [20, 21]]))??? 自帶索引 列名? 若無指定

"{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']???? 坐標值

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ù)的作用是在原始列中重命名實現(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()? 增加行用這個函數(shù)

appended = df1.append(df2)

df1.append(df3, ignore_index=True) 參數(shù)不加會引起索引的不連續(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ù),還有幾個

afterdrop = ss.drop(['ABT', 'ACN'])? 把行里面的選定標簽給去掉了

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')???? 將普通列設置為索引列

reindexed = subset.reindex(index=['MMM', 'ABBV', 'FOO'])? 重新設置行索引的位置和內(nèi)容

subset.reindex(columns=['Price','Book Value','New Col'])? 可以用于列的索引標簽

Hierarchical indexing?? 叫層次化索引吧,英語不好

reindexed = sp500.reset_index()? 先將源索引貶職,

multi_fi = reindexed.set_index(['Sector', 'Symbol'])? 在設置多個索引,按順序的這是

one_mon_hist.mean()?? 默認為列的均值

one_mon_hist.mean(axis=1)??? 計算為行的均值

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()? ? 每一個唯一值得個數(shù)。

pd.read_csv()? function:這個函數(shù)用于讀取數(shù)據(jù)

msft = pd.read_csv("data/msft.csv", index_col=0) 指定索引

msft.dtypes? 查看數(shù)據(jù)類型之后

msft = pd.read_csv("data/msft.csv",dtype = { 'Volume' : np.float64})? 改變數(shù)據(jù)類型

df = pd.read_csv("data/msft.csv",header=0,names=['open', 'high', 'low','close', 'volume', 'adjclose']) 修飾列名,header=0 表示跳過首行,必須有,不然以后會出問題 可能

df2 = pd.read_csv("data/msft.csv",usecols=['Date', 'Close'],index_col=['Date'])? 指定列,索引

df2.to_csv("data/msft_modified.csv", index_label='date')? 存儲數(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])? 跳過那幾行

df = pd.read_csv("data/msft_with_footer.csv",skip_footer=2,engine = 'python') 跳過最后兩行

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'])? 以上的整合,就不寫意思了

df = pd.read_excel("data/stocks.xlsx")

aapl = pd.read_excel("data/stocks.xlsx", sheetname='aapl') 讀取指定表

df.to_excel("data/stocks2.xls")??? 存儲

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') ? 多個表的操作

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") ? ? 反正沒弄成,在編譯器上報網(wǎng)址錯誤


但要記住這個方法,,或記住有這個方法

Reading and writing from/to SQL? databases? 這一站等過幾天學習生sql的時候在回過來 看吧


從遠程數(shù)據(jù)服務器上讀取數(shù)據(jù)

import pandas.io.data as web?? 改了,,會報錯

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]? 能理解意思上面的基礎操作就沒有白學習

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ù)

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容