二維陣列

Python 金融入門

Adina Howe

Professor

二維陣列

import numpy as np

months = [1, 2, 3]
prices = [238.11, 237.81, 238.91]
cpi_array = np.array([months, prices])

print(cpi_array)
[[   1.      2.      3.  ]
 [ 238.11  237.81  238.91]]
Python 金融入門

陣列方法

print(cpi_array)
[[   1.      2.      3.  ]
 [ 238.11  237.81  238.91]]

.shape」會回傳陣列的維度

print(cpi_array.shape)
(2, 3)

.size」會回傳陣列的總元素數

print(cpi_array.size)
6
Python 金融入門

陣列函式

import numpy as np

prices = [238.11, 237.81, 238.91]
prices_array = np.array(prices)

np.mean()」計算輸入的平均值

print(np.mean(prices_array))
238.27666666666667

np.std()」計算輸入的標準差

print(np.std(prices_array))
0.46427960923946671
Python 金融入門

`arange()` 函式

numpy.arange() 會依起點、終點、步長建立陣列

import numpy as np

months = np.arange(1, 13)

print(months)
[ 1  2  3  4  5  6  7  8  9 10 11 12]
months_odd = np.arange(1, 13, 2)

print(months_odd)
[ 1  3  5  7  9 11]
Python 金融入門

`transpose()` 函式

numpy.transpose() 會對 numpy 陣列進行列、欄互換

print(cpi_array)
[[   1.      2.      3.  ]
 [ 238.11  237.81  238.91]]
cpi_transposed = np.transpose(cpi_array)
print(cpi_transposed)
[[   1.    238.11]
 [   2.    237.81]
 [   3.    238.91]]
Python 金融入門

二維陣列的索引

print(cpi_array)
[[   1.      2.      3.  ]
 [ 238.11  237.81  238.91]]
# row index 1, column index 2 
cpi_array[1, 2]
238.91
# all row slice, third column
print(cpi_array[:, 2])
[   3.    238.91]
Python 金融入門

一起來練習吧!

Python 金融入門

Preparing Video For Download...