二維數組的表示方法:
python原生:列表的列表
Numpy:ndarray
Pandas:DataFrame
二維ndarray與Python List
1.ndarry性能更好
2.ndarray有mean()、std()、sum()等更多的跟數學計算相關的內置函數,作用於整個數組
3.訪問語法差別:a[1,2](Numpy ndarray)、a[1][2](Python List)
Numpy的軸
axis的用法:
0:按列計算
1:按行計算
import numpy as np
arr = np.array([
[27.93,28.18,29.39,40.52,26.26],
[58.08,50.61,51.62,48.55,54.03],
[38.67,31.73,57.91,59.24,49.08],
[45.83,31.48,45.94,71.21,46.53],
[70.26,55.96,53.81,58.48,43.23],
[46.61,22.73,45.77,63.63,56.73],
[49.73,40.47,69.13,55.16,58.71],
[34.02,42.02,28.75,34.90,26.43],
[56.64,31.39,43.43,54.00,44.97],
[57.28,64.21,55.70,68.03,54.16]
])
#某一天所有店的情況(某行)
print(arr[1,:])
#某一天幾個店的情況(某行)
print(arr[1,1:3])
#某家店十天的情況(某列)
print(arr[:,3])
#計算第一天銷量最大的店10天平均銷量
print(arr[:,arr[0,:].argmax()].mean())
#所有水果店的天均銷量
for i in range(5):
print(arr[i,:].mean())
#axis用法
print(arr.mean(axis=1))
#計算每家水果店平均銷量
for i in range(5):
print(arr[:,i].mean())
#axis用法
print(arr.mean(axis=0))
舉例:
# 輸入一個二維數組的某個元素的座標,計算出以這個元素爲左上角元素的2*2小矩陣的四個元素的均值。
#
# 比如,對於矩陣
#
# [[1, 2, 3, 4],
# [5, 6, 7, 8],
# [9, 10, 11, 12],
# [13, 14, 15, 16]]
#
# 當輸入(0, 1)(即左上角行編號爲0,列編號爲1)時,計算結果爲4.5(2,3,6,7四個數字的平均數)。
squre = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
def mini_squre(squre, top_row, left_column):
return squre[ top_row:top_row + 2, left_column:left_column + 2 ].mean()
input_top = int(input("輸入左上角行編號:"))
input_left = int(input("輸入左上角列編號:"))
if (input_top >= 0 and input_top <= len(squre[:, 0]) - 2 and
input_left >= 0 and input_left <= len(squre[0, :]) - 2):
print(mini_squre(squre, input_top, input_left))