淺談python中常用的8種經(jīng)典數(shù)據(jù)結(jié)構(gòu)
- python原生數(shù)據(jù)結(jié)構(gòu):元組Tuple(),列表List[],集合Set{},字典Dictionary{A:B};
- NumPy包中的數(shù)據(jù)結(jié)構(gòu):數(shù)組Ndarray(帶多種操作),矩陣Matrix(多種線性代數(shù)計算);
- Pandas包中的數(shù)據(jù)結(jié)構(gòu):序列Series(索引+1列數(shù)據(jù)),數(shù)據(jù)框DataFrame(索引+多列數(shù)據(jù)表)。
NumPy包中的數(shù)據(jù)結(jié)構(gòu)
NumPy中的數(shù)據(jù)結(jié)構(gòu),包括Ndarray、Matrix
數(shù)組(Ndarray)
創(chuàng)建Ndarray
- 引入NumPy包,將其命名為np。在引入NumPy包后方可使用數(shù)組數(shù)據(jù)結(jié)構(gòu)
import numpy as np
創(chuàng)建數(shù)組對象,在NumPy包中:
- array() 方法可以把序列型對象轉(zhuǎn)換成數(shù)組;
- arange() 方法可以生成自定義終點的一堆數(shù)組;
- ones 生成值全為1的數(shù)組;
- empty() 方法會生成一個給定類型和維度且不進行數(shù)據(jù)初始化的數(shù)組;
- random() 生成隨機數(shù)組;
- linspace() 生成指定起止數(shù)值和步長的一維數(shù)組,例如生成一個從1到10的元素個數(shù)為5的數(shù)組
import numpy as np array001 = np.array([1,2,3,4,5,6,7,8,9,10,11,12]) a2 = np.arange(5) a3 = np.ones((2,2)) a4 = np.empty((2,2)) a5 = np.random.rand(4,2) a6 = np.linspace(10,30,5) print('\n序列型數(shù)據(jù)轉(zhuǎn)化得到數(shù)組:',array001, '\n顯示該數(shù)據(jù)結(jié)構(gòu)類型:',type(array001), '\narange()函數(shù)創(chuàng)建的數(shù)組:',a2, '\nones()函數(shù)創(chuàng)建的全1數(shù)組:\n',a3, '\nempty()函數(shù)創(chuàng)建的未賦值的數(shù)組:\n',a4, '\nrandom()函數(shù)創(chuàng)建的隨機數(shù)組:\n',a5, '\nlinespace()函數(shù)創(chuàng)建的隨機數(shù)組:',a6)
序列型數(shù)據(jù)轉(zhuǎn)化得到數(shù)組: [ 1 2 3 4 5 6 7 8 9 10 11 12]
顯示該數(shù)據(jù)結(jié)構(gòu)類型: <class 'numpy.ndarray'>
arange()函數(shù)創(chuàng)建的數(shù)組: [0 1 2 3 4]
ones()函數(shù)創(chuàng)建的全1數(shù)組:
[[1. 1.]
[1. 1.]]
empty()函數(shù)創(chuàng)建的未賦值的數(shù)組:
[[0. 0.]
[0. 0.]]
random()函數(shù)創(chuàng)建的隨機數(shù)組:
[[0.39902074 0.63298526]
[0.09231821 0.23007193]
[0.09899536 0.83000881]
[0.27760961 0.65135898]]
linespace()函數(shù)創(chuàng)建的隨機數(shù)組: [10. 15. 20. 25. 30.]
Ndarray查詢操作
數(shù)組可以通過 array[a:b] 從數(shù)組中提取子集,也可以在此基礎(chǔ)上進行批量賦值操作。
array002 = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) print('\n一維數(shù)組索引:',array001[4:], '\n二維數(shù)組索引:',array002[1:3,2:4]) #2-3行、3-4列
一維數(shù)組索引: [ 5 6 7 8 9 10 11 12]
二維數(shù)組索引: [[ 7 8] [11 12]]
以下均為多維數(shù)組中的常用屬性,其中,shape 可以返回對象的數(shù)據(jù)結(jié)構(gòu),例如行數(shù)與列數(shù),除了返回一個表示數(shù)組各維度的元組,也可以通過 reshape 改變數(shù)組的結(jié)構(gòu)
array004 = array001.reshape(3,-1) print('\n改變結(jié)構(gòu)后的數(shù)組\n',array004, '\n數(shù)組各個維度:',array004.shape, '\n數(shù)組結(jié)構(gòu)類型:',array004.dtype, '\n數(shù)組數(shù)據(jù)個數(shù):',array004.size, '\n數(shù)組數(shù)據(jù)類型字節(jié)數(shù):',array004.itemsize, '\n數(shù)組維度:',array004.ndim)
改變結(jié)構(gòu)后的數(shù)組
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
數(shù)組各個維度: (3, 4)
數(shù)組結(jié)構(gòu)類型: int32
數(shù)組數(shù)據(jù)個數(shù): 12
數(shù)組數(shù)據(jù)類型字節(jié)數(shù): 4
數(shù)組維度: 2
Ndarray增加操作
- append() 函數(shù)可以增加元素或者列表類型的數(shù)據(jù),但必須注意維度需要保持一致。
array003 = np.append(array002,[[1],[2],[3]],axis = 1) # axis = 1 按列方向添加 print('\n增加一列后的數(shù)組\n',array003)
增加一列后的數(shù)組
[[ 1 2 3 4 1]
[ 5 6 7 8 2]
[ 9 10 11 12 3]]
Ndarray 刪除操作
- 使用 delete(x,i,axis=) 方法可以刪除數(shù)組對象中行或者列,第三個參數(shù) axis 決定了刪除的是行還是列,需要刪除的對象可以是一個數(shù),也可以是一個元組。
array003 = array002.T print('刪除單行后的數(shù)組:\n',np.delete(array003,1,axis=0)) # axis=0刪除行 array003 = array002.T print('批量刪除后的數(shù)組:\n',np.delete(array003,(1,3),0)) array003 = array002.T print('刪除單列后的數(shù)組\n',np.delete(array003,1,1)) # axis=1刪除列
刪除單行后的數(shù)組:
[[ 1 5 9]
[ 3 7 11]
[ 4 8 12]]
批量刪除后的數(shù)組:
[[ 1 5 9]
[ 3 7 11]]
刪除單列后的數(shù)組
[[ 1 9]
[ 2 10]
[ 3 11]
[ 4 12]]
Ndarray修改
- 可以使用索引的方式進行數(shù)組數(shù)據(jù)的批量修改。
array002[1:2]=0 print('數(shù)組批量賦值\n',array002) array003 = array002.T array003[1][1] = 100 print('修改數(shù)值后的數(shù)組\n',array003)
數(shù)組批量賦值
[[ 1 2 3 4]
[ 0 0 0 0]
[ 9 10 11 12]]
修改數(shù)值后的數(shù)組
[[ 1 0 9]
[ 2 100 10]
[ 3 0 11]
[ 4 0 12]]
Ndarray其它操作
1.二維數(shù)組轉(zhuǎn)置。array.T 可以得到數(shù)組對象轉(zhuǎn)置后的結(jié)果
2.數(shù)組的堆疊。首先新進兩個數(shù)組,之后依次使用 vstack 進行縱向堆疊和使用 hstack 進行橫向堆疊
arr1 = np.array([1,2,3]) arr2 = np.array([4,5,6]) print('縱向堆疊后:\n',np.vstack((arr1,arr2)), '\n橫向堆疊后:\n',np.hstack((arr1,arr2)))
縱向堆疊后:
[[1 2 3]
[4 5 6]]
橫向堆疊后:
[1 2 3 4 5 6]
Ndarray轉(zhuǎn)化成其它數(shù)據(jù)結(jié)構(gòu)
arr3 = np.array([[1,2,3],[4,5,6]]) print('轉(zhuǎn)換前的Ndarray是:\n',arr3) import pandas as pd dfFromNdarray = pd.DataFrame(arr3) print('Ndarray轉(zhuǎn)化為DataFrame的結(jié)果是:\n',dfFromNdarray) #帶行號和列號
轉(zhuǎn)換前的Ndarray是:
[[1 2 3]
[4 5 6]]
Ndarray轉(zhuǎn)化為DataFrame的結(jié)果是:
0 1 2
0 1 2 3
1 4 5 6
arrFromDataFrame = dfFromNdarray.values print('DataFrame轉(zhuǎn)化為Ndarry的結(jié)果是:\n',arrFromDataFrame) #只提取value值
DataFrame轉(zhuǎn)化為Ndarry的結(jié)果是:
[[1 2 3]
[4 5 6]]
矩陣(Matrix)
創(chuàng)建Matrix
- 使用mat()方法可以把其他數(shù)據(jù)結(jié)構(gòu)的對象轉(zhuǎn)換為矩陣類型。
array1 = [1,2,3] array2 = [6,7,8] array3 = [11,12,17] matrix = np.mat([array1,array2,array3]) print('顯示該數(shù)據(jù)結(jié)構(gòu)類型:',type(matrix)) print(matrix)
顯示該數(shù)據(jù)結(jié)構(gòu)類型: <class 'numpy.matrix'>
[[ 1 2 3]
[ 6 7 8]
[11 12 17]]
創(chuàng)建隨機矩陣,在numpy中包含了許多創(chuàng)建特殊矩陣的方法,這里使用 empty() 方法創(chuàng)建一個新的數(shù)據(jù)隨機的矩陣
matrix1 = np.empty((3,3)) print(matrix1)
[[ 0.00000000e+000 0.00000000e+000 0.00000000e+000]
[ 0.00000000e+000 0.00000000e+000 2.27270197e-321]
[ 9.30350261e+199 1.10343781e-312 -3.38460783e+125]]
Matrix查詢操作
- 在矩陣中有一下常用屬性用于觀察矩陣
print('矩陣每維的大?。?,matrix.shape) print('矩陣所有數(shù)據(jù)的個數(shù):',matrix.size) print('矩陣每個數(shù)據(jù)的類型:',matrix.dtype)
矩陣每維的大?。?nbsp;(3, 3)
矩陣所有數(shù)據(jù)的個數(shù): 9
矩陣每個數(shù)據(jù)的類型: int32
Matrix增加操作
- 矩陣合并。c_() 方法進行連接,根據(jù)參數(shù)順序也將決定生產(chǎn)矩陣的結(jié)果;r_() 方法用于列連接。
mat1 = np.mat([[1,2],[3,4]]) mat2 = np.mat([4,5]) matrix_r = np.c_[mat1,mat2.T] print('將mat2矩陣添加在原矩陣右側(cè)\n',matrix_r) matrix_l = np.c_[mat2.T,mat1] print('將mat2矩陣添加在原矩陣左側(cè)\n',matrix_l) matrix_u = np.r_[np.mat([array1]),matrix] print('在原矩陣上方連接矩陣\n',matrix_u)
將mat2矩陣添加在原矩陣右側(cè)
[[1 2 4]
[3 4 5]]
將mat2矩陣添加在原矩陣左側(cè)
[[4 1 2]
[5 3 4]]
在原矩陣上方連接矩陣
[[ 1 2 3]
[ 1 2 3]
[ 6 7 8]
[11 12 17]]
Matrix刪除操作
- delete() 方法可以刪除矩陣的指定行列,具體類似數(shù)組中的用法。
matrix2 = np.delete(matrix,1,axis = 1) print('刪除第一行后的結(jié)果\n',matrix2) matrix3 = np.delete(matrix,1,axis=0) print('刪除第一列后的結(jié)果\n',matrix3)
刪除第一行后的結(jié)果
[[ 1 3]
[ 6 8]
[11 17]]
刪除第一列后的結(jié)果
[[ 1 2 3]
[11 12 17]]
Matrix特殊操作
1.矩陣運算,在矩陣運算中,* 被重寫用于矩陣乘法,dot() 則用于計算矩陣點乘
2.如果需要對應(yīng)位置相乘,則需使用其它函數(shù)。
mat3 = np.mat([[5,6],[7,8]]) matrix4 = mat1*mat3 print('矩陣乘法結(jié)果\n',matrix4) matrix5 = mat1.dot(mat3) print('矩陣點乘結(jié)果\n',matrix5)
矩陣乘法結(jié)果
[[19 22]
[43 50]]
矩陣點乘結(jié)果
[[19 22]
[43 50]]
矩陣常用函數(shù)。矩陣也可以使用 .T 進行轉(zhuǎn)置。linalg.inv() 可以用于求逆運算,若不存在逆矩陣則報錯。
matrix6 = matrix.T matrix7 = np.linalg.inv(mat1) print('\n矩陣轉(zhuǎn)置后:\n',matrix6, '\n矩陣求逆后:\n',matrix7)
矩陣轉(zhuǎn)置后:
[[ 1 6 11]
[ 2 7 12]
[ 3 8 17]]
矩陣求逆后:
[[-2. 1. ]
[ 1.5 -0.5]]
求矩陣特征值(使用numpy必須是方陣)
matrix8 = np.linalg.eig(matrix) print(matrix8)
(array([24.88734753, -0.8418908 , 0.95454327]), matrix([[-0.1481723 , -0.87920199, 0.10036602],
[-0.4447565 , 0.3814255 , -0.82855015],
[-0.88331004, 0.28551435, 0.550846 ]]))
Matrix轉(zhuǎn)換為其它數(shù)據(jù)結(jié)構(gòu)
由于結(jié)構(gòu)相似,矩陣常常與列表和數(shù)組進行數(shù)據(jù)類型轉(zhuǎn)換。
print('矩陣列表轉(zhuǎn)換:\n',matrix.tolist(), '\n矩陣轉(zhuǎn)數(shù)組:\n',np.array(matrix))
矩陣列表轉(zhuǎn)換:
[[1, 2, 3], [6, 7, 8], [11, 12, 17]]
矩陣轉(zhuǎn)數(shù)組:
[[ 1 2 3]
[ 6 7 8]
[11 12 17]]
Pandas中的數(shù)據(jù)結(jié)構(gòu),包括Series和DataFrame
序列(Series)
創(chuàng)建Series
- 引入Pandas包并取別名pd
import pandas as pd
- 首先建立一個字典,使用 Series() 方法將字典轉(zhuǎn)換成序列對象,字典的key會自動成為series的index;若轉(zhuǎn)換列表,則生產(chǎn)的序列對象會自動賦予index值。
sdata = {'Ohio':35000,'Texas':71000,'Oregon':16000,'Utah':5000} s0 = pd.Series(sdata) print('利用字典生成的序列對象\n',s0) print('顯示該數(shù)據(jù)結(jié)構(gòu)類型:',type(s0)) s1 = pd.Series([6,1,2,9]) print('利用列表生成的序列對象\n',s1)
利用字典生成的序列對象
Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
dtype: int64
顯示該數(shù)據(jù)結(jié)構(gòu)類型: <class 'pandas.core.series.Series'>
利用列表生成的序列對象
0 6
1 1
2 2
3 9
dtype: int64
- 添加索引,通過指定index為series增加索引
s1 = pd.Series([6,1,2,9],index=['a','b','c','d']) print(s1)
a 6
b 1
c 2
d 9
dtype: int64
Series查詢操作
- values 顯示series中的值,index 顯示索引,此外還可以按照索引值顯示元素。
print('序列的值\n',s0.values) print('序列的索引\n',s0.index) print('按照下標(biāo)查找序列',s0[2]) print('按照索引值查找元素',s0['Utah']) print('按照下標(biāo)批量查找序列\(zhòng)n',s0[:2]) print('按照索引值批量查找元素\n',s0[['Ohio','Oregon']])
序列的值
[35000 71000 16000 5000]
序列的索引
Index(['Ohio', 'Texas', 'Oregon', 'Utah'], dtype='object')
按照下標(biāo)查找序列 16000
按照索引值查找元素 5000
按照下標(biāo)批量查找序列
Ohio 35000
Texas 71000
dtype: int64
按照索引值批量查找元素
Ohio 35000
Oregon 16000
dtype: int64
Series增加操作
- append() 方法為series增加元素,index可以指定索引值。
s2 = s1.append(pd.Series([12],index=['e'])) print(s2)
a 6
b 1
c 2
d 9
e 12
dtype: int64
Series刪除操作
- 刪除Series中的元素(只能通過index來刪除元素)
s3 = s1.drop('a') print(s3)
dtype: int64
b 1
c 2
d 9dtype: int64
Series修改操作
- 序列中可以直接根據(jù)索引查找并更新元素。
s1['a'] = 4 #將s1中index為a的元素更改為4 print(s1)
a 4
b 1
c 2
d 9
dtype: int64
Series特殊操作
- 序列排序。sort_values()方法可以使用series的值按照升序排序。
print(s1.sort_values)
a 4
b 1
c 2
d 9
dtype: int64>
- 序列求中位數(shù)。median()方法可以直接得到序列的中位數(shù),在此之上可以進行比較等操作。
print(s1) print('中位數(shù)為:'+str(s1.median())) print('大于序列中位數(shù)的數(shù)\n',s1[s1>s1.median()])
中位數(shù)為:3.0
大于序列中位數(shù)的數(shù)
a 4
d 9
dtype: int64
- 序列的運算,兩個series之間的運算,可以加減乘除(必須保證index是一致的)。
s2 = pd.Series([4,3,5,8],index=['a','b','c','d']) print(s2+s1)
a 8
b 4
c 7
d 17
dtype: int64
- 時間序列。pandas包中的data_range()方法可以生成時間序列,便于進行數(shù)據(jù)的處理。
s3 = pd.Series([100,150,200]) print('產(chǎn)生的序列是:\n',s3) idx = pd.date_range(start='2019-9',freq='M',periods=3) print('\n生成的時間序列是:\n',idx) s3.index = idx print('\n產(chǎn)生的時間序列是:\n',s3)
產(chǎn)生的序列是:
0 100
1 150
2 200
dtype: int64生成的時間序列是:
DatetimeIndex(['2019-09-30', '2019-10-31', '2019-11-30'], dtype='datetime64[ns]', freq='M')產(chǎn)生的時間序列是:
2019-09-30 100
2019-10-31 150
2019-11-30 200
Freq: M, dtype: int64
Series轉(zhuǎn)換為其它數(shù)據(jù)結(jié)構(gòu)
dfFromSeries = s2.to_frame() print('Series轉(zhuǎn)DataFrame\n',dfFromSeries) print('顯示數(shù)據(jù)結(jié)構(gòu)類型:',type(dfFromSeries))
Series轉(zhuǎn)DataFrame
0
a 4
b 3
c 5
d 8
顯示數(shù)據(jù)結(jié)構(gòu)類型: <class 'pandas.core.frame.DataFrame'>
dictFromSeries = s2.to_dict() print('Series轉(zhuǎn)Dict\n',dictFromSeries) print('顯示數(shù)據(jù)結(jié)構(gòu)類型:',type(dictFromSeries))
Series轉(zhuǎn)Dict
{'a': 4, 'b': 3, 'c': 5, 'd': 8}
顯示數(shù)據(jù)結(jié)構(gòu)類型: <class 'dict'>
數(shù)據(jù)框(DataFrame)
創(chuàng)建DataFrame
引入pandas包,創(chuàng)建DataFrame對象。首先創(chuàng)建字典,之后使用 DataFrame() 方法創(chuàng)建數(shù)據(jù)框?qū)ο?。通過index.name給其索引命名。最后使用 to_csv 和 to_excel 方法將其保存為csv和excel文件;也可以用列表進行創(chuàng)建:pd.DataFrame(data,columns,index)。
dic1 = {'name':['Tom','Lily','Cindy','Petter'],'no':['001','002','003','004'],'age':[16,16,15,16],'gender':['m','f','f','m']} df1 = pd.DataFrame(dic1) print('顯示該數(shù)據(jù)結(jié)構(gòu)類型',type(df1)) df1.index.name = 'id' #df1.to_csv('students.csv') #df1.to_excel('students.xls') ?。?!會報錯 print(df1)
顯示該數(shù)據(jù)結(jié)構(gòu)類型 <class 'pandas.core.frame.DataFrame'>
name no age gender
id
0 Tom 001 16 m
1 Lily 002 16 f
2 Cindy 003 15 f
3 Petter 004 16 m
DataFrame 查詢操作
- 通過 DataFrame.name 可以返回索引值為name的整列數(shù)據(jù),而 DataFrame.loc[i] 可以返回指定行數(shù)的全部數(shù)據(jù)。除此之外也可以使用根據(jù)時間序列查找內(nèi)容。
- ?。?!loc[ ] 按列名稱 iloc[ ] 按列號 操作
- 獲取列索引:df.cloums
- 獲取行索引:df.index
- 獲取值:df.value
column = df1.no row = df1.loc[3] print('\n列數(shù)據(jù)索引\n',column,'\n行數(shù)據(jù)索引\n',row)
列數(shù)據(jù)索引
id
0 001
1 002
2 003
3 004
Name: no, dtype: object
行數(shù)據(jù)索引
name Petter
no 004
age 16
gender m
Name: 3, dtype: object
DataFrame增加操作
- 使用 append() 方法增加一名同學(xué)的信息,這里根據(jù)行索引分別添加值。update() 方法可以給數(shù)據(jù)框增加列。
print('修改前:\n',df1) df2 = df1.append([{'name':'Stark','no':'005','age':15,'gender':'m'}],ignore_index=True) #接著索引號為4,不寫的話就是0 print('增加行:\n',df2) df2['new_Col'] = [1,2,3,4,5] print('增加列:\n',df2)
修改前:
name no age gender
id
0 Tom 001 16 m
1 Lily 002 16 f
2 Cindy 003 15 f
3 Petter 004 16 m
增加行:
name no age gender
0 Tom 001 16 m
1 Lily 002 16 f
2 Cindy 003 15 f
3 Petter 004 16 m
4 Stark 005 15 m
增加列:
name no age gender new_Col
0 Tom 001 16 m 1
1 Lily 002 16 f 2
2 Cindy 003 15 f 3
3 Petter 004 16 m 4
4 Stark 005 15 m 5
DataFrame刪除操作
- 使用 drop 方法刪除'address'列,還可以通過修改參數(shù)刪除行。除此之外通過 del 指令可以刪除指定索引值的整列數(shù)據(jù)(操作一旦進行即不可回復(fù))。
df3 = df1.copy() print('處理前的數(shù)據(jù)\n',df1) df3b = df3.drop(['name'],axis=1) print('刪除列后的數(shù)據(jù)框\n',df3b) df3c = df3.drop([2]) print('刪除行后的數(shù)據(jù)框\n',df3c)
處理前的數(shù)據(jù)
name no age gender
id
0 Tom 001 16 m
1 Lily 002 16 f
2 Cindy 003 15 f
3 Petter 004 16 m
刪除列后的數(shù)據(jù)框
no age gender
id
0 001 16 m
1 002 16 f
2 003 15 f
3 004 16 m
刪除行后的數(shù)據(jù)框
name no age gender
id
0 Tom 001 16 m
1 Lily 002 16 f
3 Petter 004 16 m
DataFrame修改操作
- 數(shù)據(jù)框按列合并(效果和增加列相同)
df4 = pd.DataFrame({'address':['school','home','school','school','home']}) df5 = pd.concat([df2,df4],axis=1) print('合并前的df2\n',df2) print('合并前的df4\n',df4) print('合并后的df5\n',df5)
合并前的df2
name no age gender new_Col
0 Tom 001 16 m 1
1 Lily 002 16 f 2
2 Cindy 003 15 f 3
3 Petter 004 16 m 4
4 Stark 005 15 m 5
合并前的df4
address
0 school
1 home
2 school
3 school
4 home
合并后的df5
name no age gender new_Col address
0 Tom 001 16 m 1 school
1 Lily 002 16 f 2 home
2 Cindy 003 15 f 3 school
3 Petter 004 16 m 4 school
4 Stark 005 15 m 5 home
- 數(shù)據(jù)框按行合并(效果和增加學(xué)生信息相同)
df6 = pd.DataFrame({'name':['Tony'],'no':['005'],'age':[16],'gender':['m']}) df7 = pd.concat([df1,df6],axis=0) print('合并前的df1\n',df1) print('合并前的df6\n',df6) print('合并后的df7\n',df7)
合并前的df1 name no age gender id 0 Tom 001 16 m 1 Lily 002 16 f 2 Cindy 003 15 f 3 Petter 004 16 m 合并前的df6 name no age gender 0 Tony 005 16 m 合并后的df7 name no age gender 0 Tom 001 16 m 1 Lily 002 16 f 2 Cindy 003 15 f 3 Petter 004 16 m 0 Tony 005 16 m
DataFrame 特殊操作
- 數(shù)據(jù)框的時間序列。通過 date_range 函數(shù)生成序列并加入數(shù)據(jù)中,列如創(chuàng)建從2019年9月21日開始的連續(xù)4天的時間序列。使用pandas包中的 read_csv() 方法讀取之前保存的學(xué)生數(shù)據(jù),更新數(shù)據(jù)后可以看到生成的時間序列已經(jīng)加入到了數(shù)據(jù)框中
i1 = pd.date_range('2019/9/21',periods=4,freq='7D') df10 = pd.read_csv('students.csv') df10.index = i1 print(df10)
id name no age gender
2019-09-21 0 Tom 1 16 m
2019-09-28 1 Lily 2 16 f
2019-10-05 2 Cindy 3 15 f
2019-10-12 3 Petter 4 16 m
時間序列查詢
print('\n根據(jù)時間序列索引得到的值\n',df10.loc['2019-09-21':'2019-09-30',['gender','age','name']])
根據(jù)時間序列索引得到的值
gender age name
2019-09-21 m 16 Tom
2019-09-28 f 16 Lily
DataFrame轉(zhuǎn)換為其它數(shù)據(jù)結(jié)構(gòu)
print('DataFrame轉(zhuǎn)ndarray\n',df10.values, '\nDataFrame轉(zhuǎn)series\n',df10['gender'])
DataFrame轉(zhuǎn)ndarray
[[0 'Tom' 1 16 'm']
[1 'Lily' 2 16 'f']
[2 'Cindy' 3 15 'f']
[3 'Petter' 4 16 'm']]
DataFrame轉(zhuǎn)series
2019-09-21 m
2019-09-28 f
2019-10-05 f
2019-10-12 m
Freq: 7D, Name: gender, dtype: object
python原生數(shù)據(jù)結(jié)構(gòu)
元組(Tuple)
- 使用()、tuple()創(chuàng)建元組,元組可以為空且元素類型可以不同;
- 若元組中僅包含一個數(shù)字,則應(yīng)該添加逗號以區(qū)別運算符號:tup=(1,);
- 元組一旦創(chuàng)建就無法對其元素進行增加、刪除、修改。
Tuple查詢操作
- 元組可以使用下標(biāo)索引來訪問元組中的值。
tup1=('Google','Runoob',1997,2000) tup2=(1,) #創(chuàng)建單個數(shù)字元組 print("tup1[0]:",tup1[0]) #訪問元組中第一各元素 print("tup2[1:5]:",tup2[1:5])
tup1[0]: Google
tup2[1:5]: ()
Tuple整體刪除操作
- 使用del方法可以刪除指定的元組對象,但無法刪除指定下標(biāo)的元組元素。
Tuple連接和復(fù)制
- 雖然元組中的元素不允許修改,但可以對元組進行連接組合創(chuàng)建出一個新的元組。
tup3=tup1+tup2 tup4=tup2*3 #復(fù)制三份
Tuple其它操作
- len() 返回元組元素個數(shù);
- max()/min() 返回元組元素中的最大、最小元素。
Tulpe轉(zhuǎn)換為其它數(shù)據(jù)結(jié)構(gòu)(舉例)
- 元組可以轉(zhuǎn)換為字符串、列表……不過單個元組無法直接轉(zhuǎn)換成字典
print("\n元組轉(zhuǎn)列表:\n",list(tup1), "\n元組轉(zhuǎn)字符串:\n",tup1.__str__())
列表(List)
創(chuàng)建列表
- 一維列表的創(chuàng)建。使用[]可以創(chuàng)建一個列表對象,列表是一種有序的集合,可以隨時添加和刪除其中的元素;
- 多維列表的創(chuàng)建。盡管list默認(rèn)是一維的,但可以使用[]嵌套創(chuàng)建多維列表。
List查詢操作
- list[a:b] 返回列表中第a個至第b-1個元素的列表對象;
- list[::a] 返回一個從列表第一個元素開始,步長為a的列表對象;
- list[i] 返回列表中下標(biāo)為i的元素,若i為負(fù)數(shù),則從列表尾部從后至前訪問第i個元素。
List增加操作
- append() 可以在列表末尾增加新的項目,可以增加一個元素,也可以增加一個list對象成為多維列表。
List刪除操作
- remove() 函數(shù)可以刪除指定值的元素,list.remove(i)會刪除list對象中值為i的元素,若不存在則報錯;
- pop() 函數(shù)可以刪除指定下標(biāo)的元素,默認(rèn)為列表對象的最后一個元素,list.pop(i)將刪除下標(biāo)為i的元素。
List修改操作
- list[i]=x 可以直接替換列表中指定下標(biāo)的元素
List其它操作
- reverse() 函數(shù)可以使列表倒置;
- len() 函數(shù)可以返回列表的元素個數(shù);
- sort() 函數(shù)可以使列表元素升序排列。
List轉(zhuǎn)換為其它數(shù)據(jù)結(jié)構(gòu)
- 列表可以便利的轉(zhuǎn)換為各種數(shù)據(jù)類型;注意,單個列表無法轉(zhuǎn)換為字典。
集合(Set)
創(chuàng)建Set
- 集合不會出現(xiàn)重復(fù)值,所有元素按照一定的順序排列,若元素為數(shù)字則按數(shù)字大小排列,使用set()函數(shù)創(chuàng)建集合會自動的拆分多個字母組成的字符串
myset = set('aabc') #使用set()函數(shù)創(chuàng)建集合會自動的拆分多個字母組成的字符串 print(myset) myset1 = set(('hello','world')) print(myset1)
{'a', 'c', 'b'}
{'hello', 'world'}
Set 查詢操作
- 使用in可以判斷a是否在集合中,存在為真,反之為假。
'a' in myset
Set 增加操作
- add() 函數(shù)可以在集合對象中加入新元素,若元素已存在,則無效果;
- 使用update表示添加(并非修改)是一個一個添加,并且按照順序添加進集合。
myset.add('ghk') myset.update('tyu') #一個一個元素添加 print(myset)
{'t', 'b', 'a', 'ghk', 'c', 'y', 'u'}
Set刪除操作
- remove() 函數(shù)可以將集合中的元素刪除,元素不存在會報錯;
- discard() 函數(shù)可以刪除集合中指定的元素,且元素不存在不報錯;
- pop() 函數(shù)可以隨機刪除集合中的一個元素(在交互模式下刪除最后一個元素);
- clear() 函數(shù)可以清空集合。
Set其它操作
- len() 函數(shù)可以查詢集合的長度;
- copy() 可以復(fù)制集合中的元素并生成一個新的集合
copy_myset=myset.copy() print('\nlen()返回集合的長度:',len(myset), '\ncopy()生成的集合:',copy_myset)
len()返回集合的長度: 7
copy()生成的集合: {'a', 'c', 'u', 't', 'ghk', 'b', 'y'}
- 集合的運算。首先建立兩個集合用于運算,在集合運算中,‘-’表示求差,‘&’表示求和,‘|’表示求并集,'^'表示兩個集合的并集減去交集
a = set('apple') b = set('banana') print ('\n求差集:',a-b, '\n求并集:',a|b, '\n求交集:',a&b, '\n求各自獨特的:',a^b)
求差集: {'e', 'p', 'l'}
求并集: {'p', 'n', 'l', 'a', 'b', 'e'}
求交集: {'a'}
求各自獨特的: {'n', 'p', 'l', 'b', 'e'}
字典(Dictionary)
創(chuàng)建Dict
- 生成一個字典和一個包含三個字典對象的字典列表。(列表中嵌套字典,students實際上是一個列表,students中的元素是字典)
dict1={"ID":"L100","Name":"COCO"} students = [{'name':'n1','id':'001'},{'name':'n2','id':'002'},{'name':'n3','id':'003'}] print("顯示該數(shù)據(jù)結(jié)構(gòu)類型",type(dict1)) print(dict1)
顯示該數(shù)據(jù)結(jié)構(gòu)類型 <class 'dict'>
{'ID': 'L100', 'Name': 'COCO'}
- 使用zip方法創(chuàng)建字典。zip() 方法可以返回元組組成的列表,可以用于快速構(gòu)建字典。
demo_dict = dict(zip('abc','123')) print(demo_dict)
{'a': '1', 'b': '2', 'c': '3'}
Dict查詢操作
- 查找第一個學(xué)生的學(xué)號(顯示出第一個字典元素id鍵的值);此外還可以使用get(key,default=None)方法獲取指定鍵的值。
print('常規(guī)查詢:',students[0]['id']) print('根據(jù)鍵查詢:',students[0].get('id'))
常規(guī)查詢: 001
根據(jù)鍵查詢: 001
Dict增加操作
- 添加一名學(xué)生的信息(增加行,其實是增加列表中一個元素),之后再添加一個學(xué)生信息科目(增加列,其實就是增加字典中一個鍵值對)
students.append({'name':'n4','id':'004'}) print('添加一個字典對象后:',students) students[0]['school']='school1' students[1]['school']='school2' students[2]['school']='school2' print('增加鍵值對后的字典:',students)
添加一個字典對象后: [{'name': 'n1', 'id': '001'}, {'name': 'n2', 'id': '002'}, {'name': 'n3', 'id': '003'}, {'name': 'n4', 'id': '004'}]
增加鍵值對后的字典: [{'name': 'n1', 'id': '001', 'school': 'school1'}, {'name': 'n2', 'id': '002', 'school': 'school2'}, {'name': 'n3', 'id': '003', 'school': 'school2'}, {'name': 'n4', 'id': '004'}]
Dict刪除操作
- 使用del刪除一名學(xué)生的信息(刪除行,其實就是刪除列表中的一個元素)。再使用pop刪除第一個學(xué)生的學(xué)號(刪除某一行中的列,其實是刪除字典中的一個鍵值對)
del students[3] #刪除第4行(下標(biāo)為3) print('刪除列表中的一個字典對象后:\n',students) students[0].pop('id') print('刪除一個鍵值對后:\n',students)
刪除列表中的一個字典對象后
[{'name': 'n1', 'id': '001', 'school': 'school1'}, {'name': 'n2', 'id': '002', 'school': 'school2'}, {'name': 'n3', 'id': '003', 'school': 'school2'}]
刪除一個鍵值對后
[{'name': 'n1', 'school': 'school1'}, {'name': 'n2', 'id': '002', 'school': 'school2'}, {'name': 'n3', 'id': '003', 'school': 'school2'}]
- 刪除所有學(xué)生的學(xué)號(刪除某一列,其實就是刪除所有字典中的一個鍵值對)
for i in range(0,len(students)): students[i].pop('school') print(students)
[{'name': 'n1'}, {'name': 'n2', 'id': '002'}, {'name': 'n3', 'id': '003'}]
Dict修改操作
- 添加(更改)第一個學(xué)生的學(xué)號(在列表的第一個字典元素中增加/更改鍵值對)
students[0].update({'id':'001'}) print('\n更新后的字典\n',students)
更新后的字典
[{'name': 'n1', 'id': '001'}, {'name': 'n2', 'id': '002'}, {'name': 'n3', 'id': '003'}]
Dict轉(zhuǎn)換為其它數(shù)據(jù)結(jié)構(gòu)
- 字典的鍵和值可以被單獨各自轉(zhuǎn)換為list
print("字典值轉(zhuǎn)List:",list(demo_dict.values())) print("字典鍵轉(zhuǎn)List:",list(demo_dict.keys()))
字典值轉(zhuǎn)List: ['1', '2', '3']
字典鍵轉(zhuǎn)List: ['a', 'b', 'c']
到此這篇關(guān)于淺談python中常用的8種經(jīng)典數(shù)據(jù)結(jié)構(gòu)的文章就介紹到這了,更多相關(guān)python經(jīng)典數(shù)據(jù)結(jié)構(gòu)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Python實現(xiàn)在Windows下安裝Django
今天小編就為大家分享一篇關(guān)于使用Python實現(xiàn)在Windows下安裝Django,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10windows下安裝Python虛擬環(huán)境virtualenvwrapper-win
這篇文章主要介紹了windows下安裝Python虛擬環(huán)境virtualenvwrapper-win,內(nèi)容超簡單,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06Python機器學(xué)習(xí)利用隨機森林對特征重要性計算評估
本文是對隨機森林如何用在特征選擇上做一個簡單的介紹。隨機森林非常簡單,易于實現(xiàn),計算開銷也很小,更令人驚奇的是它在分類和回歸上表現(xiàn)出了十分驚人的性能2021-10-10python在回調(diào)函數(shù)中獲取返回值的方法
今天小編就為大家分享一篇python在回調(diào)函數(shù)中獲取返回值的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02Python將視頻或者動態(tài)圖gif逐幀保存為圖片的方法
本文是基于opencv將視頻和動態(tài)圖gif保存為圖像幀的方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友參考下吧2019-09-09使用anaconda的pip安裝第三方python包的操作步驟
今天小編就為大家分享一篇使用anaconda的pip安裝第三方python包的操作步驟,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06