1. 程式人生 > >Python學習(6):pandas

Python學習(6):pandas

一.Series建立
1.直接建立

s=pd.Series([1,3,6,np.nan,44,1])

2.可以在建立Series時新增index,並可使用Series.index檢視具體的index。需要注意的一點是,當從陣列建立Series時,若指定index,那麼index長度要和data一致。

k=pd.Series(np.random.randn(5),index=['a','b','c','d','e'])
print (k.index)

3.Series還可以從字典(dict)建立

d ={'a': 0.,'b': 1,'c':2}
s=Series(d)

建立時指定index

Series(d.,index =['b','c','d','a'] )

使用字典建立Series時指定index,資料將按index的順序重新排列,且index長度可以和字典長度不一致,多了的話pandas自動為多餘的index分配NaN(not a number),當然index少的話就擷取部分的字典內容

d ={'a': 0.,'b': 1,'c':2}
m=pd.Series(d)
pd.Series(m,inde=['b','c','d','a'])

如果資料就是一個單一的變數,那麼Series將重複這個變數

Series(4,index=['a','b','c','d','e'])

二.Series資料的訪問
1.Series可以使用下標,也可以像字典一樣使用索引,還可以使用條件過濾

s=pd.Series(np.random.randn(10),index=['a','b','c','d','e','f','g','h','i','j'])
print (s[0])
#從0開始輸出兩個元素
s[:2]
#按第3,1,5的順序輸出
print (s[[2,0,4]])
#按索引的順序輸出
s[['e','i']]
#輸出大於0.5的資料
s[s > 0.5]

三.建立DataFrame
DataFrame是一個二維的資料結構,是多個Series的幾何體。我們先建立一個值是Series的字典,並轉換維DataFrame:
利用Series建立:

d = {'one':pd.Series([1.,2.,3.],index=['a','b','c']),'two':pd.Series([1.,2.,3.,4.],index=['a','b','c','d'])}
df2 = pd.DataFrame(d)
print (df2)

可以指定所需的行和列,若字典中不含有對應的元素,則置為NaN。

d = {'one':pd.Series([1.,2.,3.],index=['a','b','c']),'two':pd.Series([1.,2.,3.,4.],index=['a','b','c','d'])}
df2 =pd.DataFrame(d,index=['r','d','a'],columns=['two','three'])

DataFrame也可以從值是陣列的字典建立,但是各個陣列的長度需要相同,值非陣列時,沒有這一限制。

在這裡插入程式碼片

在實際處理資料時,有時需要建立一個空的DataFrame,可以這麼做: