1. 程式人生 > >02 ndarray的屬性 、ndarray的基本操作(索引、切片、變形、連線、切分、副本)、聚合操作、矩陣操作、排序、Panda資料結構、Series建立、索引與切片、屬性與方法、運算

02 ndarray的屬性 、ndarray的基本操作(索引、切片、變形、連線、切分、副本)、聚合操作、矩陣操作、排序、Panda資料結構、Series建立、索引與切片、屬性與方法、運算

二、ndarray的屬性

4個必記引數:

ndim:維度

shape:形狀(各維度的長度)

size:總長度

dtype:元素型別

import matplotlib.pyplot as plt
ndarr = plt.imread("./jin.png")
plt.imshow(ndarr)
# 接下來展示的是幾個屬性 
ndarr.ndim # 多少個維度
ndarr.shape # 形狀 273 411 3
ndarr.size # 總共有多少個元素 273*411*3
ndarr.dtype

在這裡插入圖片描述

三、ndarray的基本操作

1. 索引

基本索引:一維與列表完全一致 多維時同理

ndarr = np.random.randint(0,10,size=(4,5)) 
# 二維陣列 陣列中有4個元素(陣列) 這4個數組中分別有 5個元素
ndarr
結果為:
array([[2, 4, 1, 8, 1],
       [5, 1, 6, 8, 5],
       [0, 2, 1, 6, 6],
       [2, 3, 9, 0, 5]])
ndarr[0] #按照索引就可以把元素取出   array([2, 4, 1, 8, 1])
ndarr[1]    					    array([5, 1, 6, 8, 5])
ndarr[1][3]							8
ndarr[1][-2]                        8

高階索引:整數陣列形式的索引

ndarr = np.random.randint(0,10,size=(4,5)) # 二維陣列 陣列中有4個元素(陣列) 這4個數組中分別有 5個元素
ndarr
結果為:
array([[8, 5, 5, 6, 4],
       [0, 1, 7, 6, 8],
       [7, 4, 2, 9, 1],
       [9, 4, 6, 2, 4]])
ndarr[0][0]                      8
ndarr[0,0] # 多維陣列還支援 整數陣列的形式 作為索引			8
ndarr[2,3]						9
ndarr[2,-2]						9
list1 = [[0, 8, 2, 9, 3],
 		[9, 2, 3, 0, 1],
 		[9, 1, 0, 6, 7],
 		[2, 7, 6, 5, 4]]	      
list1[0][0]
list1[0,0] # 注意整數陣列索引是 ndarray特有的索引方式 list沒有
結果顯示:TypeError: list indices must be integers or slices, not tuple

練習:使用陣列索引尋找指定位置的值

nd = np.random.randint(0,10,size=(2,4,3,7)) 
nd
結果為:
array([[[[8, 5, 6, 9, 6, 9, 6],
         [6, 4, 1, 3, 4, 1, 7],
         [1, 9, 9, 0, 3, 2, 6]],

        [[6, 3, 8, 7, 1, 8, 8],
         [1, 9, 5, 4, 0, 2, 9],
         [4, 7, 0, 2, 9, 9, 1]],

        [[1, 5, 8, 4, 0, 1, 4],
         [6, 1, 7, 4, 5, 8, 9],
         [6, 2, 2, 1, 0, 6, 5]],

        [[2, 3, 5, 0, 4, 9, 0],
         [6, 1, 6, 5, 1, 5, 8],
         [7, 2, 9, 0, 3, 0, 5]]],


       [[[9, 1, 7, 9, 5, 2, 3],
         [6, 2, 7, 2, 7, 1, 9],
         [6, 8, 6, 6, 4, 3, 9]],

        [[1, 9, 7, 6, 0, 7, 8],
         [2, 3, 9, 7, 7, 2, 2],
         [9, 7, 7, 7, 0, 4, 3]],

        [[7, 6, 2, 2, 4, 5, 4],
         [5, 9, 3, 6, 3, 6, 4],
         [1, 6, 1, 9, 0, 0, 4]],

        [[1, 7, 2, 3, 4, 1, 6],
         [0, 5, 3, 8, 3, 0, 3],
         [9, 9, 8, 5, 7, 9, 4]]]])
nd[0,0,0,4]			6
nd[0,0,0,-3]		6
nd[0,0,2,0]			1
nd[0,2,1,-3]		5
  1. 切片

一維與列表切片完全一致 多維時同理

nd = np.random.randint(0,10,size=(5,4))
nd
結果為:
array([[3, 9, 6, 6],
       [1, 1, 5, 8],
       [6, 9, 5, 4],
       [6, 7, 9, 5],
       [4, 1, 2, 8]])
nd[0:3] # start:end [start:end)
結果為:
array([[3, 9, 6, 6],
       [1, 1, 5, 8],
       [6, 9, 5, 4]])
nd[:3] # 如果從0開始 0可以省略  與上面結果保持一致
nd[1:] # 如果取到最後 後面的值可以省略
array([[1, 1, 5, 8],
       [6, 9, 5, 4],
       [6, 7, 9, 5],
       [4, 1, 2, 8]])
nd[1:3] # 從第0行取到弟2行
結果為:
array([[1, 1, 5, 8],
       [6, 9, 5, 4]])
nd[1:3,0:2] # 從外往裡 層層切片  從第0行取到弟2行且列數為第0列取到第一列
結果為:
array([[1, 1],
       [6, 9]])
nd[0:4:2,0:4:2]
結果為:
array([[3, 6],
       [6, 5]])
nd[::2,::2]  #每行每列挑一行或一列取
結果為:
array([[3, 6],
       [6, 5],
       [4, 2]])
nd[::-1]  #把外圍元素即每行的順序顛倒
結果為:
array([[4, 1, 2, 8],
       [6, 7, 9, 5],
       [6, 9, 5, 4],
       [1, 1, 5, 8],
       [3, 9, 6, 6]])
nd[:,::-1] #把裡圍元素即每列的順序顛倒
結果為:
array([[6, 6, 9, 3],
       [8, 5, 1, 1],
       [4, 5, 9, 6],
       [5, 9, 7, 6],
       [8, 2, 1, 4]])

練習:取項尚人頭

jin = plt.imread("./123.jpg")
plt.imshow(jin)
jin.shape
plt.imshow(jin[25:150,175:260])

結果為:

在這裡插入圖片描述

兩個:: 的形式 進行切片和翻轉

nd
結果為:
array([[3, 9, 6, 6],
       [1, 1, 5, 8],
       [6, 9, 5, 4],
       [6, 7, 9, 5],
       [4, 1, 2, 8]])
nd[::2] #start:end:step #每行隔一行取
結果為:
array([[3, 9, 6, 6],
       [6, 9, 5, 4],
       [4, 1, 2, 8]])
nd[1:4:2] #從第0行取到第三行 且每行隔一行取
結果為:
array([[1, 1, 5, 8],
       [6, 7, 9, 5]])
nd[::2,::2] #每行每列隔一行取
結果為:
array([[3, 6],
       [6, 5],
       [4, 2]])
nd[:,::-2] #每列從右向左隔一行取
結果為:
array([[6, 9],
       [8, 1],
       [4, 9],
       [5, 7],
       [8, 1]])

練習: 圖片的上下顛倒 左右顛倒 變瘦 色值的交換

jin = plt.imread("./jin.png")
plt.imshow(jin)
jin.shape
plt.imshow(jin[::-1]) # 翻轉了最外圍 上下顛倒
plt.imshow(jin[:,::-1]) # 左右顛倒
plt.imshow(jin[::-1,::-1]) # 旋轉180度
plt.imshow(jin[:,::3]) # 變瘦
# 紅 綠 藍 # 藍 綠 紅
plt.imshow(jin[:,:,::-1]) # 藍精靈
# 紅 綠 藍 
plt.imshow(jin[:,:,[1,0,2]]) # 綠巨人

3. 變形

使用reshape函式,注意引數是一個tuple!

np
結果為:
array([[3, 9, 6, 6],
       [1, 1, 5, 8],
       [6, 9, 5, 4],
       [6, 7, 9, 5],
       [4, 1, 2, 8]])

nd.shape			結果為:(5, 4)
nd.reshape((4,5)) # 改變形狀 注意引數是一個元組
nd.reshape((2,10)) # 不止可以顛倒行列 只要元素總是一樣 都可以變形
nd.reshape((2,8)) # 總數一樣可以變形 總數不一樣就會報錯了

4. 連結

  1. np.concatenate() 連結需要注意的點:
  2. 連結的引數是列表:一定要加小括號
  3. 維度必須相同
  4. 形狀相符
  5. 連結的方向預設是shape這個tuple的第一個值所代表的維度方向
  6. 可通過axis引數改變連結的方向
nd
結果為:
array([[3, 9, 6, 6],
       [1, 1, 5, 8],
       [6, 9, 5, 4],
       [6, 7, 9, 5],
       [4, 1, 2, 8]])
nd2 = np.random.randint(0,10,size=(2,4))
nd2

結果為:
array([[1, 7, 6, 6],
       [0, 6, 4, 8]])
np.concatenate((nd,nd2))
結果為:
array([[3, 9, 6, 6],
       [1, 1, 5, 8],
       [6, 9, 5, 4],
       [6, 7, 9, 5],
       [4, 1, 2, 8],
       [1, 7, 6, 6],
       [0, 6, 4, 8]])
np.concatenate((nd,nd2),axis=1) # 形狀要相符

5. 切分

與級聯類似,三個函式完成切分工作:

  • np.split
  • np.vsplit
  • np.hsplit
ndarr = np.random.randint(0,10,size=(4,4))
ndarr
結果為:
array([[4, 2, 0, 6],
       [4, 0, 4, 4],
       [0, 0, 3, 4],
       [4, 2, 9, 6]]
# 引數 1.要切分的陣列 2.要分成幾份 3切分時候的軸
np.split(ndarr,2) # axis預設是0
結果為:
array([[4, 2, 0, 6],
        [4, 0, 4, 4]]),
array([[0, 0, 3, 4],
        [4, 2, 9, 6]])]
np.split(ndarr,2,axis=1) 
結果為:
[array([[4, 2],
        [4, 0],
        [0, 0],
        [4, 2]]), array([[0, 6],
        [4, 4],
        [3, 4],
        [9, 6]])]
np.vsplit(ndarr,2) # v vertical 垂直 對垂直方向的元素進行切割(切割的時候是水平去切的)
結果為:
[array([[4, 2, 0, 6],
        [4, 0, 4, 4]]), array([[0, 0, 3, 4],
        [4, 2, 9, 6]])]
np.hsplit(ndarr,2) # h horizon 水平 對水平方向上的元素進行切割(切的時候垂直切)
結果為:
[array([[4, 2],
        [4, 0],
        [0, 0],
        [4, 2]]), array([[0, 6],
        [4, 4],
        [3, 4],
        [9, 6]])]
ndarr
結果為:
array([[4, 2, 0, 6],
       [4, 0, 4, 4],
       [0, 0, 3, 4],
       [4, 2, 9, 6]])
np.split(ndarr,[1,3])
結果為:
[array([[4, 2, 0, 6]]), array([[4, 0, 4, 4],
        [0, 0, 3, 4]]), array([[4, 2, 9, 6]])]

6. 副本

所有賦值運算不會為ndarray的任何元素建立副本。對賦值後的物件的操作也對原來的物件生效。

ndarr
結果為:
array([[4, 2, 0, 6],
       [4, 0, 4, 4],
       [0, 0, 3, 4],
       [4, 2, 9, 6]])
ndarr1 = ndarr
print(id(ndarr),id(ndarr1))
結果為:
134475984 134475984

可使用copy()函式建立副本

ndarr2 = ndarr.copy() #多維陣列呼叫自身的copy()方法 就會返回一個一模一樣 但是完全獨立的陣列
print(id(ndarr),id(ndarr2))
134475984 130613536

四、ndarray的聚合操作

1. 求和np.sum

2. 最大最小值:np.max/ np.min

3. 其他聚合操作

Function Name    NaN-safe Version    Description
np.sum    np.nansum    Compute sum of elements 所有元素的和
np.prod    np.nanprod    Compute product of elements 所有元素的乘積
np.mean    np.nanmean    Compute mean of elements
np.std    np.nanstd    Compute standard deviation
np.min    np.nanmin    Find minimum value
np.max    np.nanmax    Find maximum value
np.argmin    np.nanargmin    Find index of minimum value
np.argmax    np.nanargmax    Find index of maximum value
np.median    np.nanmedian    Compute median of elements
np.power 冪運算
np.any    N/A    Evaluate whether any elements are true
np.all    N/A    Evaluate whether all elements are true

ndarr
結果為:
array([[6, 4, 2, 2],
       [1, 8, 2, 7],
       [0, 9, 3, 9],
       [7, 0, 4, 0]])
np.sum(ndarr)										64
np.any(ndarr) # any 只要元素中有True就是True 0是False 其他都是True
結果為:True
np.all(ndarr) # all 必須所有元素都是True才是True 0是False 其他都是True
結果為:
False 
ndarr = np.random.randint(0,10,size=(4,6))
ndarr
結果為:
array([[3, 6, 1, 0, 1, 4],
       [2, 0, 3, 1, 5, 1],
       [2, 5, 4, 6, 4, 0],
       [6, 1, 3, 6, 2, 9]])
np.any(ndarr,axis=1)
array([False, False, False,  True])
np.any(ndarr,axis=-1)
array([False, False, False,  True]
np.any(ndarr,axis=0) #只要有true就是True
結果為:
array([ True,  True,  True,  True,  True,  True])
# any和all將來可以用來做資料過濾
ndarr
結果為:
array([[9, 6, 8, 5, 8, 9],
       [6, 0, 0, 4, 1, 3],
       [1, 8, 9, 0, 3, 2],
       [4, 0, 2, 3, 9, 1]])
# 按照條件到多維陣列中尋找
np.argwhere(ndarr == 0) # 返回要找的值的位置
結果為:
array([[1, 1],
       [1, 2],
       [2, 3],
       [3, 1]], dtype=int64)
np.argwhere(ndarr > 8) 
結果為:
array([[0, 0],
       [0, 5],
       [2, 2],
       [3, 4]], dtype=int64)

np.sum 和 np.nansum 的區別 nan not a number

ndarr2 = np.array([1,2,3,np.NAN])
ndarr2
結果為:
array([ 1.,  2.,  3.,  4.,  5., nan])
np.sum(ndarr2) # 運算中 只要遇到nan結果就是nan  結果為:nan
# 如果不希望是nan
np.nansum(ndarr2) # 把nan當作0來參與運算   結果為:15.0
array([ 1.,  2.,  3., nan])

操作檔案

使用pandas開啟檔案president_heights.csv 獲取檔案中的資料

import pandas as pd
data = pd.read_csv("./president_heights.csv")
data

在這裡插入圖片描述

type(data)         pandas.core.frame.DataFrame
type(data.values)    numpy.ndarranumpy.ndarray

五、ndarray的矩陣操作

1. 基本矩陣操作

  1. 算術運算子:
  • 加減乘除
import numpy as np
ndarr = np.random.randint(0,10,size=(4,5))
ndarr
結果為:
array([[4, 7, 6, 2, 3],
       [6, 5, 2, 0, 4],
       [0, 7, 8, 9, 4],
       [4, 2, 7, 8, 5]])
# 矩陣和數值的運算
ndarr + 1 # 矩陣和數值做加法 給矩陣中所有的值都加上這個數 廣播機制
ndarr - 1 # 矩陣中每一個值都減這個數值
ndarr * 2 # 每個值都乘以這個數值
ndarr / 2 #
  1. 矩陣積np.dot()

點積 是 第一個的行和第二個的列做運算,第二個矩陣的行數必須等於第一個矩陣的列數 這樣 前後兩組數字才能對應上

ndarr
結果為:
array([[4, 7, 6, 2, 3],
       [6, 5, 2, 0, 4],
       [0, 7, 8, 9, 4],
       [4, 2, 7, 8, 5]])
 ndarr.shape       (4, 5)
ndarr2 = np.random.randint(0,10,size=(5,3)) # 必須是5行
ndarr2.shape       (5, 3)
ndarr2
結果為:
array([[0, 4, 8],
       [7, 1, 7],
       [0, 7, 7],
       [0, 1, 7],
       [8, 7, 5]]
np.dot(ndarr,ndarr2)
結果為:
array([[108, 140,  65],
       [ 94, 105,  60],
       [125, 173,  92],
       [107, 161,  83]])

2. 廣播機制

【重要】ndarray廣播機制的兩條規則

  • 規則一:為缺失的維度補1
  • 規則二:假定缺失元素用已有值填充

例1: m = np.ones((2, 3)) a = np.arange(1,4,1) 求m+a

m = np.ones((2, 3))
m
結果為:
array([[1., 1., 1.],
       [1., 1., 1.]])
a = np.arange(1,4,1)
a
結果為:array([1, 2, 3])
a+m
結果為:
array([[2., 3., 4.],
       [2., 3., 4.]])

例2: a = np.arange(3).reshape((3, 1)) b = np.arange(3) 求a+b

a = np.arange(3).reshape((3, 1))
a
結果為:
array([[0],
       [1],
       [2]])
b = np.arange(3)
b
結果為:
array([0, 1, 2])
a + b
結果為:
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

習題 a = np.ones((4, 1)) b = np.arange(4) 求a+b

六、ndarray的排序

小測驗: 使用以上所學numpy的知識,對一個ndarray物件進行選擇排序。

def Sortn(x):

程式碼越短越好

1. 快速排序

np.sort()與ndarray.sort()都可以,但有區別:

  • np.sort()不改變輸入
  • ndarray.sort()本地處理,不佔用空間,但改變輸入
nadrr
結果為:
array([[4, 7, 6, 2, 3],
       [6, 5, 2, 0, 4],
       [0, 7, 8, 9, 4],
       [4, 2, 7, 8, 5]])
np.sort(ndarr)  # 傳入一個數組 np.sort會返回一個新陣列 這個新陣列是從小到大排序的陣列 (原陣列不變)
結果為:
array([[2, 3, 4, 6, 7],
       [0, 2, 4, 5, 6],
       [0, 4, 7, 8, 9],
       [2, 4, 5, 7, 8]])
aandarr.sort() # 多維陣列呼叫自身的sort 會把自己按照從小到大的順序排改變自身陣列
ndarr
結果為:
array([[2, 3, 4, 6, 7],
       [0, 2, 4, 5, 6],
       [0, 4, 7, 8, 9],
       [2, 4, 5, 7, 8]])

2. 部分排序

np.partition(a,k)

有的時候我們不是對全部資料感興趣,我們可能只對最小或最大的一部分感興趣。

  • 當k為正時,我們想要得到最小的k個數
  • 當k為負時,我們想要得到最大的k個數
ndarr3 = np.random.randint(0,100,size=15)
ndarr3
結果為:
array([49, 64,  5, 28, 50, 90, 20, 26, 98, 13, 65,  0, 54, 99, 43])
np.partition(ndarr3,1)      
結果為:array([ 0,  5, 64, 28, 50, 90, 20, 26, 98, 13, 65, 49, 54, 99, 43])
np.partition(ndarr3,2)
結果為:array([ 0,  5, 13, 28, 50, 90, 20, 26, 98, 64, 65, 49, 54, 99, 43])
np.partition(ndarr3,3)
結果為:array([ 0,  5, 13, 20, 26, 28, 43, 64, 98, 90, 65, 50, 54, 99, 49])
np.partition(ndarr3,4)
結果為:array([ 0,  5, 13, 20, 26, 28, 43, 64, 98, 90, 65, 50, 54, 99, 49])
np.partition(ndarr3,-5) #最大的5個放後面
結果為:array([20, 26,  5, 28,  0, 13, 43, 50, 49, 54, 64, 98, 90, 99, 65])

Pandas的資料結構

匯入pandas:

資料分析三劍客 numpy pandas matplotlib

import pandas as pd
from pandas import Series,DataFrame
import numpy
import matplotlib.pyplot as plt

1、Series

Series是一種類似於一維陣列的物件,由下面兩個部分組成:

  • index:相關的資料索引標籤
  • values:一組資料(ndarray型別)

1)Series的建立

兩種建立方式:

(1) 由列表或numpy陣列建立

預設索引為0到N-1的整數型索引
s1 = Series([1,2,3,4])
s1
結果為:
0    1
1    2
2    3
3    4
dtype: int64
s1.index # 索引 				結果為:RangeIndex(start=0, stop=4, step=1)
s1.values # 值 值是多維數     結果為:array([1, 2, 3, 4], dtype=int64)
還可以通過設定index引數指定索引
s2 = Series([1,2,3],index=("a","b","c")) # 通過index可以指定索引 注意:索引的個數和值的個數要對應
結果為:
a    1
b    2
c    3
dtype: int64

(2) 由字典建立

s3 = Series({"A":10,"B":20,"C":30})
s3
結果為:
A    10
B    20
C    30
dtype: int64

============================================

練習1:

使用多種方法創 建以下Series,命名為s1:
語文 150
數學 150
英語 150
理綜 300

============================================

s1 = Series([150,150,150,300],index=("語文","數學","英語","理綜"))
s1
結果為:
語文    150
數學    150
英語    150
理綜    300
dtype: int64

2)Series的索引和切片

可以使用中括號取單個索引(此時返回的是元素型別),或者中括號裡一個列表取多個索引(此時返回的仍然是一個Series型別)。分為顯示索引和隱式索引:

(1) 顯式索引:

- 使用index中的元素作為索引值
- 使用.loc[](推薦)

注意,此時是閉區間

s2
結果為:
a    1
b    2
c    3
dtype: int64
s2["a"]          	 			 結果為:1
s2.loc["a"] # loc location 定位 根據傳入的索引去定位值
結果為:1
s2.loc[["a","c"]] #用於定位的中括號裡面 傳入的是一個值或者是列表
結果為:
a    1
c    3
dtype: int64

(2) 隱式索引:

- 使用整數作為索引值
- 使用.iloc[](推薦)

注意,此時是半開區間

s2[0]						 結果為:1
s2.iloc[0] # iloc index location 通過索引號去定位元素
結果為:1

根據索引對Series進行切片

============================================

練習2:

使用多種方法對練習1建立的Series s1進行索引和切片:

索引: 數學 150

切片: 語文 150 數學 150 英語 150

============================================

s1
結果為:
語文    150
數學    150
英語    150
理綜    300
dtype: int64
s1.loc["語文":"英語"]
結果為:
語文    150
數學    150
英語    150
dtype: int64
s1["語文":"英語"]
結果為:
語文    150
數學    150
英語    150
dtype: int64
s1[0:3]
結果為:
語文    150
數學    150
英語    150
dtype: int64
s1["數學"]
s1[1]
s1.loc["數學"]
s1.iloc[1]
以上四種方法都是對數學分數的索引  結果為:150

3)Series的常用屬性和方法

可以把Series看成一個定長的有序字典

可以通過shape,size,index,values等得到series的屬性

s1
結果為:
數學    150
英語    150
理綜    300
dtype: int64
s1.shape 				結果為:(4,)
s1.size					結果為:4
s1.index  
結果為:
Index(['語文', '數學', '英語', '理綜'], dtype='object')
s1.values
結果為:array([150, 150, 150, 300], dtype=int64)

可以通過head(),tail()快速檢視Series物件的樣式

s.head(2)看頭兩個 s.tail(1)看後一個

s1.head(2)
結果為:
語文    150
數學    150
dtype: int64
s1.tail(3)
結果為:
數學    150
英語    150
理綜    300
dtype: int64

當索引沒有對應的值時,可能出現缺失資料顯示NaN(not a number)的情況

s2 = Series([1,3,5,7,-2,-4,None,np.nan],index=("a","b","c","d","e","f","g","h"))
s2
結果為:
a    1.0
b    3.0
c    5.0
d    7.0
e   -2.0
f   -4.0
g    NaN
h    NaN
dtype: float64
ndarr1 = np.array([1,3,5,7,-2,-4,None,np.nan])
ndarr1
array([1, 3, 5, 7, -2, -4, None, nan], dtype=object)
# ndarr1.sum() # 多維陣列中 如果有None nan 就沒法求和
結果為:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
s2.sum() # Series的sum遇到nan可以當做0 然後求和
結果為:10.0

可以使用pd.isnull(),pd.notnull(),或自帶isnull(),notnull()函式檢測缺失資料

s2
結果為:
a    1.0
b    3.0
c    5.0
d    7.0
e   -2.0
f   -4.0
g    NaN
h    NaN
dtype: float64
s2.isnull() # 是nan則返回True
結果為:
a    False
b    False
c    False
d    False
e    False
f    False
g     True
h     True
dtype: bool
s2.notnull() # 不是nan返回True
結果為:
a     True
b     True
c     True
d     True
e     True
f     True
g    False
h    False
dtype: bool
condition = s2.isnull()
s2[condition] = -100
結果為:
a      1.0
b      3.0
c      5.0
d      7.0
e     -2.0
f     -4.0
g   -100.0
h   -100.0
dtype: float64

Series物件本身及其例項都有一個name屬性

s3 = Series([1,2,3,4,5],index=("a","b","c","d","e"),name="張三")
s3
結果為:
a    1
b    2
c    3
d    4
e    5
Name: 張三, dtype: int64
s4 = Series([1,2,3,4,5],index=("a","b","c","d","e"),name="李四")
s4
結果為:
a    1
b    2
c    3
d    4
e    5
Name: 李四, dtype: int64

4)Series的運算

(1) 適用於numpy的陣列運算也適用於Series

s4 + 50
結果為:
a    51
b    52
c    53
d    54
e    55
Name: 李四, dtype: int64
s4 * 2
結果為:
a     2
b     4
c     6
d     8
e    10
Name: 李四, dtype: int64

(2) Series之間的運算

  • 在運算中自動對齊不同索引的資料
  • 如果索引不對應,則補NaN
  • 注意:要想保留所有的index,則需要使用.add()函式
s3 + s4 # 索引對應的專案的值會相加
結果為:
a     2
b     4
c     6
d     8
e    10
dtype: int64
s1 + s3 # 兩個Series進行加和時,如果索引不對應,返回值 nan
結果為:
a    NaN
b    NaN
c    NaN
d    NaN
e    NaN
數學   NaN
理綜   NaN
英語   NaN
語文   NaN
dtype: float64

索引不對應 就出NaN 如果不喜歡這樣可以呼叫 series自身的add()方法

s1.add(s3)
結果為:
a    NaN
b    NaN
c    NaN
d    NaN
e    NaN
數學   NaN
理綜   NaN
英語   NaN
語文   NaN
dtype: float64
s1.add(s3,fill_value=0)
結果為:
a       1.0
b       2.0
c       3.0
d       4.0
e       5.0
數學    150.0
理綜    300.0
英語    150.0
語文    150.0
dtype: float64

練習3:

  1. 想一想Series運算和ndarray運算的規則有什麼不同?

    前者索引不匹配時仍可可以運算,只是會顯示nan,後者結構不同時無法運算

  2. 新建另一個索引包含“文綜”的Series s2,並與s2進行多種算術操作。思考如何儲存所有資料。