Series和DataFrame
阿新 • • 發佈:2020-07-29
•pandas資料結構介紹:
pandas中兩大主要的資料結構Series和DataFrame
Series是一種類似一維陣列的物件,它由一組資料(numpy資料型別)以及一組與之相關的資料標籤(即索引)組成,
DataFrame是一種二維資料結構,是一種表格型別的資料結構(簡單的理解像excel),每列可以是不同型別的值。既有行索引也有列索引
•Series
series是能夠儲存任意形式有標籤的一維陣列
~用列表建立一個series
1 #列表建立series 2 s1=Series(["I","love","pandas"]) 3 s1
0 I 1 love 2 pandas dtype: objec
1 s1.values#series中的值
array(['I', 'love', 'pandas'], dtype=object)
1 s1.index#series中的索引(沒新增自動生成的)
RangeIndex(start=0, stop=3, step=1)
新增標籤
1 #自創索引值 2 s2=Series(["I","love","pandas"],index=list("abc")) 3 s2
a I b love c pandas dtype: object
根據標籤獲取值
1 s2["a":"b"]
a I b love dtype: object
~用字典建立一個series
1 s={"a":2,"b":3,"c":4} 2 s3=Series(s)#k為標籤,v為值 3 s3
a 2 b 3 c 4 dtype: int64
可以對索引賦值來修改索引
1 s3.index=list("xyz") 2 s3
x 2 y 3 z 4 dtype: int64
Series運算:會自動對齊不同的索引
1 s4=Series([4,5,6],index=list("axy")) 2 s4
a 4 x 5 y 6 dtype: int64
1 s3*s4
a NaN x 10.0 y 18.0 z NaN dtype: float64
•DataFrame
DataFrame可以被看作Series組成的字典(共用同一索引)
~字典巢狀字典建立
dict1={"i":{"a":1,"b":2,"c":3},"l":{"a":"x","b":"y","c":"z"},"p":{"a":3,"b":4,"c":5}} df1=pd.DataFrame(dict1)#i、l、p為列名,a、b、c為索引 df1
1 df1["I"]#選取其中一列,看是否為series
a 1 b 2 c 3 Name: i, dtype: int64
1 type(df1["i"])
a 1 b 2 c 3 Name: i, dtype: int64
所以DataFrame的每行每列都是一個Series
1 df1.columns=list("bqp") 2 df1.index=list("dfg") 3 df1
增加列
1 df1["D"]=np.arange(3)#直接寫出列名賦值即可 2 df1
del 刪除列
1 del df1["D"] 2 df1
~列表組成的字典建立(是沒有編寫索引的)
1 dict2={"a":[1,2,3,4],"b":[3,3,4,2],"c":[4,2,4,6]} 2 df2=DataFrame(dict2,index=np.arange(4)) 3 df2
~陣列建立
1 array1=[["y","z","l"],["e","j","n"]] 2 dt3=pd.DataFrame(array1,columns=['A',"B","C"],index=['noe','two']) 3 print(dt3)
A B C noe y z l two e j n
#T用於轉置 dt3.T