標籤:second 官網文檔 simple nump esc head cas concat htm
摘要 一、建立對象 二、查看資料 三、選擇和設定 四、缺失值處理 五、相關操作 六、彙總 七、重排(Reshaping)
八、時間序列
九、Categorical類型 十、畫圖
十一、匯入和儲存資料內容
# coding=utf-8
import pandas as pd
import numpy as np
### 一、建立對象
## 1.可以傳遞一個list對象建立一個Series,Pandas會預設建立整型索引
s = pd.Series([1, 3, 5, np.nan, 6, 8])
# print s
## 2.通過傳遞一個numpy array,時間索引以及欄標籤來建立一個DataFrame
dates = pd.date_range(‘20130101‘, periods=6)
# print dates
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list("ABCD"))
# print df
## 3.通過傳遞一個能夠被轉換成類似序列結構的字典對象來建立一個DataFrame
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"})
# print df2
### 二、查看資料
## 1.查看frame中頭部和尾部的行,預設5行
# print df.head()
# print df.tail(3)
## 2.顯示索引,列和底層的numpy資料
# print df.index
# print df.columns
# print df.values
## 3.describe()函數對於資料的款素統計匯總,python中方法不能省略圓括弧
# print df.describe()
## 4.對資料的轉置
# print df.T
## 5.按軸(列)進行排序
# print df.sort_index(axis=1,ascending=False)
## 6.按值進行排序,建議使用sort_values(by=)
# print df.sort(columns="B")
# print df.sort_values(by="B")
### 三、選擇和設定
## 擷取1.選擇一個單獨的列,這將會返回一個Series,等同於df.A
# print df["A"]
## 擷取2.通過[]進行選擇,這將會對行進行切片
# print df[0:3][1:2]
# print df[0:3]
##上面的方法是通過下標[]進行訪問,下面可以.loc[]來對指定便簽進行選擇
##通過標籤選擇:1.使用便簽來擷取一個交叉的地區
# print df.loc[ dates[0] ]
##通過標籤選擇:2.通過標籤來在多個軸上進行選擇
# print df.loc[ :,["A","B"] ]
##通過標籤選擇:3.標籤切片
# print df.loc[ "20130102":"20130104",["A","B"] ]
##通過標籤選擇:4.對於返回的對象進行維度縮減
# print df.loc["20130102",["A","B"]]
##通過標籤選擇:5.擷取一個標量
# print df.loc[ dates[0],"A" ]
##通過標籤選擇:6.快速存取一個標量(at方法)
# print df.at[ dates[0],"A" ]
##通過位置選擇:1.通過傳遞數值進行位置選擇(選擇的是行)
# print df.iloc[3]
##通過位置選擇:2.通過數值進切片
# print df.iloc[3:5,0:2]
##通過位置選擇:3.通過指定一個位置的列表
# print df.iloc[ [1,2,3],[0,2] ]
##通過位置選擇:4.對行進行切片
# print df.iloc[1:3,:]
##通過位置選擇:5.對列進行切片
# print df.iloc[:,1:3]
##通過位置選擇:6.擷取特定的值
# print df.iloc[1,1]
# print df.iat[1,1]
##可以使用邏輯運算式來選擇指定的資料框
##布爾索引:1.使用一個單獨列的值來選擇資料
# print df[df.A > 0]
##布爾索引:2.使用where操作來選擇資料
# print df[ df > 0]
##布爾索引:3.使用isin()方法來過濾
# print df2[df2["E"].isin( ["test"] )]
##設定:通過一個numpy數組設定一組新值
# df.loc[ :,"E" ] = np.array( [5]*len(df) )
# print df
## reindex對索引進行改變/新增/刪除(未賦值就是pd.nan)
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ["E"])
# print df1
### 四、缺失值處理(pandas使用np.nan代替缺失值,預設不會計算)
## 1.去掉包含缺失值的行
# print df1.dropna(how="any")
## 2.對缺失值進行填充
# print df1.fillna(value=5)
## 3.判斷缺失值
# print pd.isnull()
## 五、相關操作
##apply(對資料應用函數)
# print df.apply(np.cumsum)##累積和
# print df.apply(lambda x:x.max - x.min) ##x代表當前列的一個標量
##值計數器
# print s.value_counts()
##六、彙總(aggregate)
## 1.contat(拼接,預設是全外聯)
# piece = [ df[:2],df[2:4],df[4:] ]
# print pd.concat(piece) ##預設axis=0是上下串連
# piece = [ df.loc[ :,["A","B"] ],df.loc[ :,["C","D"] ] ]
# print pd.concat(piece,axis=1) ##1是左右串連
## 2.聯表操作(join,merge)
# left = pd.DataFrame( {
# "key":["foo","foo1"],"lval":[1,2]
# } )
# right = pd.DataFrame( {
# "key":["foo","foo2"],"rval":[1,2]
# } )
# print pd.merge(left,right,how="inner",left_on=left.key,right_on=right.key) ##內聯
# print pd.merge(left,right,how="left",left_on=left.key,right_on=right.key) ##左聯
# print pd.merge(left,right,how="right",left_on=left.key,right_on=right.key) ##右聯
# print pd.merge(left,right,how="outer",left_on=left.key,right_on=right.key) ##全外聯
# print left.set_index("key").join([right.set_index("key")], how="outer") ##join根據索引串連
## 3.append(追加)
# print df.append(other=[df,df]) ##只能上下聯結
## 4.分組
# print df.groupby("A").sum()
# print df.groupbyoupby( ["A","B"] ).sum() ##層次索引
# print df.groupby([‘A‘, ‘B‘])[‘C‘].mean()
# print df.groupby(df["A"])
### 七、Reshaping
## 1.Stack
# tuples = list(zip(*[[‘bar‘, ‘bar‘, ‘baz‘, ‘baz‘,
# ‘foo‘, ‘foo‘, ‘qux‘, ‘qux‘],
# [‘one‘, ‘two‘, ‘one‘, ‘two‘,
# ‘one‘, ‘two‘, ‘one‘, ‘two‘]]))
# index = pd.MultiIndex.from_tuples(tuples, names=[‘first‘, ‘second‘])
# df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=[‘A‘, ‘B‘])
# df2 = df[:4]
# print df2
#The stack function “compresses” a level in the DataFrame’s columns to produce either:
# A Series, in the case of a simple column Index
# A DataFrame, in the case of a MultiIndex in the columns
# stacked = df2.stack()
# print stacked
# print stacked.unstack()
# print stacked.unstack(1)
# print stacked.unstack(0)
## 2.樞紐分析表
# print pd.pivot_table(df,values="D",index=["A","B"],columns="C")
### 八、時間序列
# rng = pd.date_range("1/1/2012", periods=100, freq="S")
# ts = pd.Series(np.random.randn(0, 500, len(rng)), index=rng)
# print ts.resample("5Min",how="sum")
### 九、Categorical類型
詳見此處
### 十、畫圖
詳見此處
### 十一、匯入和儲存資料
df.to_csv("data.csv")
csv = df.read_csv("data.csv")
官網文檔此處
python pandas 使用