pandas中的Series和DataFrame

  1.Series介紹及創建

  Series是一種類似與一維數組的對象,由下面兩個部分組成:

  values:一組數據(ndarray類型)

  index:相關的數據索引標籤

  創建Series的兩種方式:

  第一種:由列表或numpy數組創建:

  s1 =Series([11,22,33,44,55],index=['a1','b1','c1','d1','e1'],name='Hello world')

  print(s1)

  運行結果:

  a1 11

  b1 22

  c1 33

  d1 44

  e1 55

  Name: Hello world, dtype: int64

  a1 = np.array([11,22,33,44,55])

  s2 = Series(a1,index=['a1','b1','c1','d1','e1'],name='hello series')

  print(s2)

  運行結果:

  a1 11

  b1 22

  c1 33

  d1 44

  e1 55

  Name: hello series, dtype: int32

  第二種:由字典創建,不存在index參數設置,但是依然存在默認索引(數據源必須爲一維數據)

  dict = {'hello':12,'series':30}

  s3 = Series(data=dict)

  print(s3)

  運行結果:

  hello 12

  series 30

  dtype: int64

  2.DataFrame的介紹及創建

  DataFrame具有標記軸(行和列)的二維大小可變,可能異構的表格數據結構

  算術運算在行標籤和列標籤上對齊

  可以被認爲是Series對象的類似dict的容器

  是pandas的主要數據結構

  創建DataFrame的4種方式:

  1.使用字典創建DataFarme

  dicts = {"tag1": [90, 22, 66],'tag2': [12, 33, 66]}

  d1 = DataFrame(data=dicts, index=['a', 'b', 'c'])

  print(d1)

  運行結果:

  tag1 tag2

  a 90 12

  b 22 33

  c 66 66

  2.使用ndarray創建DataFrame

  d2 = DataFrame(data=np.random.randint(0,100,size=(3,6)),index=["one","two","three"],columns=["a","b","c","d","e","f"])

  print(d2)

  運行結果:無錫人流醫院 http://xmobile.wxbhnk120.com/

  a b c d e f

  one 62 74 51 29 98 18

  two 16 16 44 3 64 72

  three 42 94 46 60 34 59

  3.隱式構造

  最常見的方法是給DataFrame構造函數的index或者columns參數傳遞兩個或更多的數組(如下另個列的標籤數組)

  d3 = DataFrame(data=np.random.randint(0, 100, size=(2, 4)), index=['x', 'y'], columns=[['a', 'b', 'c', 'd'], ['q1', 'q2', 'q3', 'q4']])

  print(d3)

  運行結果:

  a b c d

  q1 q2 q3 q4

  x 47 26 11 8

  y 40 76 18 9

  4.顯示構造

  使用pd.MultiIndex.from_arrays數組方式

  創建了一個索引對象,該索引對象爲二層索引

  indexObj = pd.MultiIndex.from_arrays([['q1', 'q2', 'q3', 'q1'], ['a', 'b', 'c', 'd']])

  d4 = DataFrame(data=np.random.randint(0, 100, size=(2, 4)), index=['x', 'y'], columns=indexObj)

  print(d4)

  運行結果:

  q1 q2 q3 q1

  a b c d

  x 85 72 43 4

  y 8 43 55 68


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