python數據結構練習

貝葉斯估計用到的數據結構
Pandas常用到的:索引與切片,unique,value_counts(),reindex,sort_index(可以用於Seires,也可以是DataFrame,但只對index本身,index或columns本身進行排序,而不是其對應的元素進行排序),order(對Series中的值進行排序),sort_index(by=)對DataFrame中的列值進行排序!,相關係數corr,協方差cov
array與DataFrame

x=pd.Series([1,1,1,2,2,3])
print(x.unique())
print(x.value_counts())

y_train=np.array([-1,-1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1])
print(y_train[0])
# error! print(y_train.unique()) Nunpy沒有unique()與value_counts()

y=pd.DataFrame(y_train)
print(y[0])
print(y[0].value_counts())

frame=pd.DataFrame(np.arange(16).reshape((4,4)),index=['red','blue','black','green'],columns=['a','b','c','d'])
#print(frame['a'] #選擇列
print(frame['a'].value_counts()) #選擇列中元素出現的次數
print(frame.a) #選擇列
print('----以上是列')
print(frame.ix[2].value_counts()) #返回第3行內容,一行豎着顯示而已;同樣可以選擇行中元素出現的次數
print(frame.ix[[2,3]]) #返回第三行,第四行內容
print('----以上是行')
print(frame['a']['red']) #引用二維表的某個元素,先是列標籤,再行標籤!

**~~DataFrame引用元素先列後行~~ **

[1 2 3]
1    3
2    2
3    1
dtype: int64
-1
0    -1
1    -1
2     1
3     1
4    -1
5    -1
6    -1
7     1
8     1
9     1
10    1
11    1
12    1
13    1
14   -1
Name: 0, dtype: int32
 1    9
-1    6
Name: 0, dtype: int64
12    1
4     1
8     1
0     1
Name: a, dtype: int64
red       0
blue      4
black     8
green    12
Name: a, dtype: int32
----以上是列
11    1
10    1
9     1
8     1
Name: black, dtype: int64
        a   b   c   d
black   8   9  10  11
green  12  13  14  15
----以上是行
0


k近鄰算法用到的數據結構:
Numpy中經常用到:shape,reshape,random,通用函數,聚合函數,索引與切片!

import numpy as np
import pandas as pd
x=np.array([1,2,3,4])
print(x.shape[0]) #4
#print(x.shape[1]) error
y=np.array([[1,2],[2,3],[3,4]])
print(y.shape[0]) #輸出個數3
print(y.shape[1]) #輸出維度2
print(y[:,1]) #切片,相當於輸出第二列
print(y[1])# 等價於y[1,]輸出第二行

輸出
4
3
2
[2 3 4]



Python自帶的數據結構

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章