pandas的具體介紹頁面:http://pandas.pydata.org/
series 一維的數據結構
series的元素可以被賦值
首先,
import pandas as pd import numpy as np # 可以看做一維數組 sd = pd.Series([5, "tinghe", 3.17, 5.12, "i am happy",'julyedu']) sd
默認的下標是 0---n-1,直接根據下標去里面對應的內容,記得要加中括號,
也可以自己指定下標,如
sd = pd.Series([5, "tinghe", 3.17, 5.12, "i am happy",'xindongfangedu'], index=["A", "B", "C", "D", "E"]) sd
sd["A"]
輸出 5
也可以使用字典dictionary { } 注意字典的用法, 字符串,冒號:
cities = {"Beijing": 55000, "Shanghai": 60000, "Shenzhen": 50000, "Hangzhou": 20000, "Guangzhou": 30000, "Suzhou": None} apts = pd.Series(cities, name="price") apts
Beijing 55000.0 Guangzhou 30000.0 Hangzhou 20000.0 Shanghai 60000.0 Shenzhen 50000.0 Suzhou NaN Name: price, dtype: float64
# 以上寫法等價於以下 # apts = pd.Series({"Beijing": 55000, "Shanghai": 60000, "Shenzhen": 50000, # "Hangzhou": 20000, "Guangzhou": 30000, "Suzhou": None}, name="price") # apts
apts[ "Guangzhou "] 也可以用字典的性質 直接取里面的數據
30000.0
apts[ [ "Hangzhou", "Beijing", "Shenzhen" ] ] 雙層中括號,取出多個對應值 ... apts = pd.Series(cities, name="price") apts name是指定的,也可以不寫
使用list定義一個列表,作為Series的index
list("abcde") 輸出 ['a', 'b', 'c', 'd', 'e'] s = pd.Series(np.random.randn(5), index=list("abcde")) s
a -1.413697 b 0.379281 c -0.355339 d -0.700710 e -0.148403 dtype: float64
注意:個數一定要對應上
list[1:4] 是根據apts輸出的結果下標去取,與在{ }內部的順序無關 都是左閉右開 apts[[4,3,2]] 雙層括號,根據數字順序取
Shenzhen 50000.0 Shanghai 60000.0 Hangzhou 20000.0 Name: price, dtype: float64
apts[3: ] 從第三個到尾 apts[ :-2] 從頭到倒數第二個 a = [1,2,3,4,5] b = [2,3,4,5,6] a+b
兩個list可以直接拼接在一起
"Shanghai" in apts 是否在里面 輸出 True或者 False
apts.get("Beijing")
如果在里面,返回,不在里面,返回None
print(apts.get("Chongqing", 0))
不在里面,返回默認值0
less_than_50000 = apts < 50000 less_than_50000
返回的是True或者False
但是取出具體的數據方法是
apts[ less_than_50000 ]
基本的數學運算:即對Series中的每一個元素都賦值
apts ** 2 兩個乘號表幾次方 后面數字表示幾次
兩次時 等價於 np.square(apts)
cars = pd.Series({"Beijing": 300000, "Shanghai": 350000, "Shenzhen": 300000, "Tianjian": 200000, "Guangzhou": 250000, "Chongqing": 150000}) cars.astype(str) 是object類型的 # cars int64類型 # cars.astype(np.float) float64類型 也可以在 cars = pd.Series({......},dtype=float64) cars 這樣改 # 以上寫法等於 # cars = pd.Series({"Beijing": 300000, "Shanghai": 350000, "Shenzhen": 300000, # "Tianjian": 200000, "Guangzhou": 250000, "Chongqing": 150000}, dtype=np.str) # cars
apts.isnull()
Suzhou的是True,
apts[apts.isnull()] = apts.mean() # 將apts的平均值賦值給那個為NaN的 apts
dataframe 數據結構
就是一張表格
dataframe可以由一個dictionary構造得到。 也就是兩者結合
data = {'city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'], 'year': [2016, 2017, 2016, 2017, 2016, 2016], 'population': [2100, 2300, 1000, 700, 500, 500]} pd.DataFrame(data)
: 之前的代表列 的名字,之后是中括號括起來, 每一行對應相等;否則出現 “ValueError: arrays must all be same length” 錯誤
當把“population”加個 “ s ”時:
多加一列,沒錯誤:
index的下標多加一個“seven”,出現 ValueError: Shape of passed values is (4, 6), indices imply (4, 7)
也可以從幾個Series構建一個DataFrame
也可以用一個list of dicts來構建DataFrame
中括號在外面,index始終是在DataFrame()里面的
也可以:
總之,要多練練。
這個就是錯誤的:
DataFrame中已有一個df:
DataFrame元素賦值
在特定的位置元素賦值: 可以給一整列賦值:
取出行列:圖示,先行 后列
不存在:frame.rows 而是frame.index, frame.columns 可以自己設置使其好看一點
Index
默認的index
可以自己指定
e是多出來的下標,但是可以直接填充
范圍是0-5,再用其他顏色填充NAN的位置
reindex 可以指定行和列 進行排序
drop來刪除Series和DataFrame中的index,注意drop的效果不是in place的,
也就是說它會返回一個object,原來的Obejct並沒有被改變
axis=1時刪除列 axis=0時刪除行
hierarchical index
data.index
unstack和stack可以幫助我們在hierarchical indexing和DataFrame之間進行切換。
data.unstack().stack()
文件讀寫
# 讀進去文件,只能放在同一個文件件下面,該下面的文件夾 data, 放在其他的位置不行 goog = pd.read_csv("data/GOOG.csv") goog.head() df.to_csv("data/sample.tsv", sep="\t") #寫進去,不僅對csv,同時對tsv文件也可以 pd.read_csv("data/sample.tsv", sep="\t", index_col=0) # 然后再讀進來
各種繪圖技能
%matplotlib inline # 只有加了上面這一行, .plot才能畫出來圖 goog["Adj Close"].plot() # Adj Close是數據里面的參數